/*
    Static JS for Vulnerability module

    Demo code: https://github.com/roraback/Vulnerability-Mapping/blob/master/js/controls.js
*/

// Global vars
var activeWindow;
var drawerOpen = false;
var colors = {
    0: '#999999',
    1: '#ff5121',
    2: '#f4961c',
    3: '#d6b317',
    4: '#77b826',
    5: '#059346'
};
var map, parser, proj4326, resilienceLayer, populationLayer, volunteerLayer, popupControl;
var current_l0, current_l1, current_l2, current_l3;
//var current_l4;

// Load the Map asynchronously
var mapjs;
var mapjscustom;
if (S3.debug) {
    mapjscustom = ['../themes/Vulnerability/js/FeatureDoubleClick.js',
                   '../themes/Vulnerability/js/SelectFeatureDouble.js',
                   '../themes/Vulnerability/js/PanZoomBar.js',
                   '../themes/Vulnerability/js/FramedCloudLocation.js',
                   '../themes/Vulnerability/js/FramedCloudVolunteer.js'
                   //'gis/openlayers/lib/OpenLayers/Strategy/Grid.js'
                   ];
} else {
    mapjscustom = ['../themes/Vulnerability/js/OpenLayers.js'];
}
S3.gis.custom = true;
s3_gis_loadjs(S3.debug, 900913, showMap, mapjscustom);

function nameSort(a, b) {
    // Sort Hierarchical Dropdown data by Name
    a = a['n'];
    var names = [a, b['n']];
    names.sort();
    if (names[0] == a) {
        return -1;
    } else {
        return 1;
    }
}

function resilienceClass(r) {
    // Lookup the class for a value of r
    switch(r) {
        case 1:
            return 'one';
        case 2:
            return 'two';
        case 3:
            return 'three';
        case 4:
            return 'four';
        case 5:
            return 'five';
        default:
            return 'none';
    }
}

$(document).ready(function() {
    // Search Autocomplete
    var dummy_input = $('#dummy_location_search');
    var data = {
        val: dummy_input.val(),
        accept: false
    };
    var locationRepresent = function(item) {
        switch(item['level']) {
            case 'L0':
                return item['name'];
                break;
            case 'L1':
                return item['name'] + ',' + item['L0'];
                break;
            case 'L2':
                return item['name'] + ',' + item['L1'] + ',' + item['L0'];
                break;
            case 'L3':
                return item['name'] + ',' + item['L2'] + ',' + item['L1'] + ',' + item['L0'];
                break;
            //case 'L4':
            //    return item['name'] + ',' + item['L3'] + ',' + item['L2'] + ',' + item['L1'] + ',' + item['L0'];
            //    break;
            //case 'L5':
            //    return item['name'] + ',' + item['L4'] + ',' + item['L3'] + ',' + item['L2'] + ',' + item['L1'] + ',' + item['L0'];
            //    break;
            case 'None':
                // No Match
                return item['label'];
                break;
        }
        return '';
    };
    var real_input = $('#location_search');
    var throbber = $('#dummy_location_search_throbber');
    var url = S3.Ap.concat('/gis/location/search.json?location.level__ne=None&filter=~&field=name&simple=1')
    dummy_input.autocomplete({
        delay: 450,
        minLength: 2,
        source: function(request, response) {
            // Patch the source so that we can handle No Matches
            $.ajax({
                url: url,
                data: {
                    term: request.term
                },
                success: function (data) {
                    if (data.length == 0) {
                        var no_matching_records = i18n.no_matching_records;
                        data.push({
                            id: 0,
                            value: 0,
                            level: 'None',
                            label: no_matching_records
                        });
                    }
                    response(data);
                }
            });
        },
        position: {
            my: 'left bottom',
            at: 'left top'
        },
        search: function(event, ui) {
            throbber.removeClass('hidden').show();
            return true;
        },
        response: function(event, ui, content) {
            throbber.hide();
            return content;
        },
        focus: function(event, ui) {
            dummy_input.val(ui.item['name']);
            return false;
        },
        select: function(event, ui) {
            var id = ui.item.id;
            if (id) {
                dummy_input.val(ui.item['name']);
                real_input.val(id)
                          .change();
                // Read extra data for location
                $.ajax({
                    'url': S3.Ap.concat('/vulnerability/vdata/' + id),
                    'dataType': 'script'
                }).done(function(data) {
                    // Copy the vdata elements across
                    for (var prop in n) {
                        vdata[prop] = n[prop];
                    }
                    // Clear the memory
                    n = null;
                    // Zoom to location
                    v_select_region(parseInt(ui.item.level[1], 10), id);
                }).fail(function(request, status, error) {
                    if (error == 'UNAUTHORIZED') {
                        msg = i18n.gis_requires_login;
                    } else {
                        msg = request.responseText;
                    }
                    console.log(msg);
                });
            } else {
                dummy_input.val('');
                real_input.val('')
                          .change();
            }
            data.accept = true;
            return false;
        }
    })
    .data('ui-autocomplete')._renderItem = function(ul, item) {
        if (item.label) {
            // No Match
            var label = item.label;
        } else {
            var label = locationRepresent(item);
        }
        return $('<li>').data('item.autocomplete', item)
                        .append('<a>' + label + '</a>')
                        .appendTo(ul);
    };
    dummy_input.blur(function() {
        if (!real_input.val()) {
            real_input.val('');
            data.accept = true;
        }
        if (!data.accept) {
            real_input.val(data.val);
        } else {
            data.val = real_input.val();
        }
        data.accept = false;
    });

    // Indicator Names/Descriptions
    var indicators = [];
    var ratings = [];
    var li;
    var iidx = 0;
    var i, v;
    for (i in idata) {
        var _i = idata[i];
        iidx += 1;
        li = "\
        <li>\
            <div class='indicatorRatingLabel'>\
                <div class='listText'>" + _i.n + "</div>\
                <div class='popup'>\
                    <div class='popupContent'>\
                        <h3>" + _i.n + "</h3>\
                        <p>" + _i.d + "</p>\
                    </div>\
                    <div class='popupBottom'></div>\
                </div>\
            </div>\
            <div class='visRange'>\
                <div class='indicatorRange' id='visRange" + _i.i + "'>\
                    <div class='leftBox'></div>\
                    <div class='medianDot'></div>\
                    <div class='rightBox'></div>\
                </div>\
            </div>\
        </li>";
        ratings.push(li);
        li = "\
        <li>\
            <div class='indicatorRatingLabel'>\
                <input name='analysisIndicators' type='radio' value='" + _i.i + "' checked>\
                <div class='listText'>" + _i.n + "</div>\
                <div class='popup'>\
                    <div class='popupContent'>\
                        <h3>" + _i.n + "</h3>\
                        <p>" + _i.d + "</p>\
                    </div>\
                    <div class='popupBottom'></div>\
                </div>\
            </div>\
            <div class='indicatorRating' id='indicatorRating" + iidx + "'></div>\
        </li>";
        indicators.push(li);
    }
    $('#indicatorRatingChart ul').html(ratings.join(''));
    $('#regionIndicators ul').html(indicators.join(''));
    $('#indicatorSelector ul').html(indicators.join(''));

    // Hierarchical Dropdowns
    // Provide the initial options
    var values = [];
    for (var prop in vdata) {
        v = vdata[prop];
        v['id'] = prop;
        values.push(v);
    }
    values.sort(nameSort);
    var res, selected;
    for (i=0; i < values.length; i++) {
        v = values[i];
        res = resilienceClass(v['r']);
        var id = v['id'];
        if (id == start) {
            selected = ' selected="selected"';
        } else {
            selected = '';
        }
        if (v['l'] === 0) {
            $('#l0_select, #l0_reports, #l0_datas, #l0_analysis1s').append('<option value="' + id + '" class="' + res + '"' + selected + '>' + v['n'] + '</option>');
            $('#l0_analysis2s, #l0_analysis3s').append('<option value="' + id + '" class="' + res + '">' + v['n'] + '</option>');
        } else if (v['l'] == 1) {
            $('#l1_select, #l1_reports, #l1_datas, #l1_analysis1s').append('<option value="' + id + '" class="' + res + '">' + v['n'] + '</option>');
        }
    }
    if (start) {
        $('#l1_analysis2, #l1_analysis3').hide();
    } else {
        $('#l1, #l1_report, #l1_data, #l1_analysis1, #l1_analysis2, #l1_analysis3').hide();
    }
    $('#l2, #l2_report, #l2_data, #l2_analysis1, #l2_analysis2, #l2_analysis3').hide();
    $('#l3, #l3_report, #l3_data, #l3_analysis1, #l3_analysis2, #l3_analysis3').hide();
    //$('#l4, #l4_report, #l4_data, #l4_analysis1, #l4_analysis2, #l4_analysis3').hide();
    // Selection (non-analysis)
    $('#l0_select, #l0_reports, #l0_datas').change(function() {
        for (var l=1; l <= 3; l++) {
            $('#l' + l + ', #l' + l + '_report, #l' + l + '_data, #l' + l + '_analysis1').hide();
            $('#l' + l + '_select, #l' + l + '_reports, #l' + l + '_datas, #l' + l + '_analysis1s').val('');
        }
        var id = this.value;
        if (id) {
            $('#lx_select_throbber, #lx_report_throbber, #lx_data_throbber').removeClass('hidden').show();
            var h = hdata[id];
            // Clear the old L1 values
            $('#l1_select, #l1_reports, #l1_datas, #l1_analysis1s').html('<option value="" selected="selected" class="none">Choose ' + h.l1 + '</option>');
            // Populate the L1
            if (typeof vdata[id].i === 'undefined') {
                // We don't have this vdata, so read it
                readHierarchy(id, 0, false);
            } else {
                lx_select(id, 0, false);
            }
        }
        indicatorsCheckCommune();
    });
    $('#l1_select, #l1_reports, #l1_datas').change(function() {
        for (var l=2; l <= 3; l++) {
            $('#l' + l + ', #l' + l + '_report, #l' + l + '_data, #l' + l + '_analysis1').hide();
            $('#l' + l + '_select, #l' + l + '_reports, #l' + l + '_datas, #l' + l + '_analysis1s').val('');
        }
        var id = this.value;
        if (id) {
            $('#lx_select_throbber, #lx_report_throbber, #lx_data_throbber').removeClass('hidden').show();
            var h = hdata[$('#' + this.id.replace('1', '0')).val()];
            // Clear the old L2 values
            $('#l2_select, #l2_reports, #l2_datas, #l2_analysis1s').html('<option value="" selected="selected" class="none">Choose ' + h.l2 + '</option>');
            // Populate the L2s
            if (typeof vdata[id].i === 'undefined') {
                // We don't have this vdata, so read it
                readHierarchy(id, 1, false);
            } else {
                lx_select(id, 1, false);
            }
        }
        indicatorsCheckCommune();
    });
    $('#l2_select, #l2_reports, #l2_datas').change(function() {
        // Could be simplified, but then harder to migrate to L4s later
        for (var l=3; l <= 3; l++) {
            $('#l' + l + ', #l' + l + '_report, #l' + l + '_data, #l' + l + '_analysis1').hide();
            $('#l' + l + '_select, #l' + l + '_reports, #l' + l + '_datas, #l' + l + '_analysis1s').val('');
        }
        var id = this.value;
        if (id) {
            $('#lx_select_throbber, #lx_report_throbber, #lx_data_throbber').removeClass('hidden').show();
            var h = hdata[$('#' + this.id.replace('2', '0')).val()];
            // Clear the old L3 values
            $('#l3_select, #l3_reports, #l3_datas, #l3_analysis1s').html('<option value="" selected="selected" class="none">Choose ' + h.l3 + '</option>');
            // Populate the L3s
            if (typeof vdata[id].i === 'undefined') {
                // We don't have this vdata, so read it
                readHierarchy(id, 2, false);
            } else {
                lx_select(id, 2, false);
            }
        }
        indicatorsCheckCommune();
    });
    $('#l3_select, #l3_reports, #l3_datas').change(function() {
        indicatorsCheckCommune();
    });
    //$('#l3_select, #l3_reports, #l3_datas').change(function() {
    //    var id = this.value;
    //    var h = hdata[$('#' + this.id.replace('3', '0')).val()];
        // Clear the old L4 values
    //    $('#l4_select, #l4_reports, #l4_datas, #l4_analysis1s').html('<option value="" selected="selected" class="none">Choose ' + h.l4 + '</option>');
        // Populate the L4s
        //if (typeof vdata[id].i === 'undefined') {
        //    // We don't have this vdata, so read it
        //    readHierarchy(id, 3, false);
        //} else {
        //    lx_select(id, 3, false);
        //}
    //});
    //$('#l4_select, #l4_reports, #l4_datas').change(function() {
    //    var id = this.value;
    //    var h = hdata[$('#' + this.id.replace('4', '0')).val()];
        // Clear the old L5 values
    //    $('#l5_select, #l5_reports, #l5_datas, #l5_analysis1s').html('<option value="" selected="selected" class="none">Choose ' + h.l5 + '</option>');
        // Populate the L5s
        //if (typeof vdata[id].i === 'undefined') {
        //    // We don't have this vdata, so read it
        //    readHierarchy(id, 4, false);
        //} else {
        //    lx_select(id, 4, false);
        //}
    //});

    // Selection (analysis)
    $('#l0_analysis1s').change(function() {
        for (var l=1; l <= 3; l++) {
            $('#l' + l + '_analysis1').hide().val('');
        }
        var id = this.value;
        if (id) {
            $('#lx_analysis1_throbber').removeClass('hidden').show();
            var h = hdata[id];
            // Clear the old L1 values
            $('#l1_analysis1s').html('<option value="" selected="selected" class="none">Choose ' + h.l1 + '</option>');
            // Populate the L1
            if (typeof vdata[id].i === 'undefined') {
                // We don't have this vdata, so read it
                readHierarchy(id, 0, 1);
            } else {
                lx_select(id, 0, 1);
            }
        } else {
            // Remove line from Graph
            analysisSelectLocation(null, 1);
        }
    });
    $('#l0_analysis2s').change(function() {
        for (var l=1; l <= 3; l++) {
            $('#l' + l + '_analysis2').hide().val('');
        }
        var id = this.value;
        if (id) {
            $('#lx_analysis2_throbber').removeClass('hidden').show();
            var h = hdata[id];
            // Clear the old L1 values
            $('#l1_analysis2s').html('<option value="" selected="selected" class="none">Choose ' + h.l1 + '</option>');
            // Populate the L1
            if (typeof vdata[id].i === 'undefined') {
                // We don't have this vdata, so read it
                readHierarchy(id, 0, 2);
            } else {
                lx_select(id, 0, 2);
            }
        } else {
            // Remove line from Graph
            analysisSelectLocation(null, 2);
        }
    });
    $('#l0_analysis3s').change(function() {
        for (var l=1; l <= 3; l++) {
            $('#l' + l + '_analysis3').hide().val('');
        }
        var id = this.value;
        if (id) {
            $('#lx_analysis3_throbber').removeClass('hidden').show();
            var h = hdata[id];
            // Clear the old L1 values
            $('#l1_analysis3s').html('<option value="" selected="selected" class="none">Choose ' + h.l1 + '</option>');
            // Populate the L1
            if (typeof vdata[id].i === 'undefined') {
                // We don't have this vdata, so read it
                readHierarchy(id, 0, 3);
            } else {
                lx_select(id, 0, 3);
            }
        } else {
            // Remove line from Graph
            analysisSelectLocation(null, 3);
        }
    });
    $('#l1_analysis1s').change(function() {
        for (var l=2; l <= 3; l++) {
            $('#l' + l + '_analysis1').hide().val('');
        }
        var id = this.value;
        if (id) {
            $('#lx_analysis1_throbber').removeClass('hidden').show();
            var h = hdata[$('#l0_analysis1s').val()];
            // Clear the old L2 values
            $('#l2_analysis1s').html('<option value="" selected="selected" class="none">Choose ' + h.l2 + '</option>');
            // Populate the L2
            if (typeof vdata[id].i === 'undefined') {
                // We don't have this vdata, so read it
                readHierarchy(id, 1, 1);
            } else {
                lx_select(id, 1, 1);
            }
        } else {
            // Update line on Graph
            analysisSelectLocation($('#l0_analysis1s').val(), 1);
        }
    });
    $('#l1_analysis2s').change(function() {
        for (var l=2; l <= 3; l++) {
            $('#l' + l + '_analysis2').hide().val('');
        }
        var id = this.value;
        if (id) {
            $('#lx_analysis2_throbber').removeClass('hidden').show();
            var h = hdata[$('#l0_analysis2s').val()];
            // Clear the old L2 values
            $('#l2_analysis2s').html('<option value="" selected="selected" class="none">Choose ' + h.l2 + '</option>');
            // Populate the L2
            if (typeof vdata[id].i === 'undefined') {
                // We don't have this vdata, so read it
                readHierarchy(id, 1, 2);
            } else {
                lx_select(id, 1, 2);
            }
        } else {
            // Update line on Graph
            analysisSelectLocation($('#l0_analysis2s').val(), 2);
        }
    });
    $('#l1_analysis3s').change(function() {
        for (var l=2; l <= 3; l++) {
            $('#l' + l + '_analysis3').hide().val('');
        }
        var id = this.value;
        if (id) {
            $('#lx_analysis3_throbber').removeClass('hidden').show();
            var h = hdata[$('#l0_analysis3s').val()];
            // Clear the old L2 values
            $('#l2_analysis3s').html('<option value="" selected="selected" class="none">Choose ' + h.l2 + '</option>');
            // Populate the L2
            if (typeof vdata[id].i === 'undefined') {
                // We don't have this vdata, so read it
                readHierarchy(id, 1, 3);
            } else {
                lx_select(id, 1, 3);
            }
        } else {
            // Update line on Graph
            analysisSelectLocation($('#l0_analysis3s').val(), 3);
        }
    });
    $('#l2_analysis1s').change(function() {
        // Could be simplified, but then harder to migrate to L4s later
        for (var l=3; l <= 3; l++) {
            $('#l' + l + '_analysis1').hide().val('');
        }
        var id = this.value;
        if (id) {
            $('#lx_analysis1_throbber').removeClass('hidden').show();
            var h = hdata[$('#l0_analysis1s').val()];
            // Clear the old L3 values
            $('#l3_analysis1s').html('<option value="" selected="selected" class="none">Choose ' + h.l3 + '</option>');
            // Populate the L3
            if (typeof vdata[id].i === 'undefined') {
                // We don't have this vdata, so read it
                readHierarchy(id, 2, 1);
            } else {
                lx_select(id, 2, 1);
            }
        } else {
            // Update line on Graph
            analysisSelectLocation($('#l1_analysis1s').val(), 1);
        }
    });
    $('#l2_analysis2s').change(function() {
        // Could be simplified, but then harder to migrate to L4s later
        for (var l=3; l <= 3; l++) {
            $('#l' + l + '_analysis2').hide().val('');
        }
        var id = this.value;
        if (id) {
            $('#lx_analysis2_throbber').removeClass('hidden').show();
            var h = hdata[$('#l0_analysis2s').val()];
            // Clear the old L3 values
            $('#l3_analysis2s').html('<option value="" selected="selected" class="none">Choose ' + h.l3 + '</option>');
            // Populate the L3
            if (typeof vdata[id].i === 'undefined') {
                // We don't have this vdata, so read it
                readHierarchy(id, 2, 2);
            } else {
                lx_select(id, 2, 2);
            }
        } else {
            // Update line on Graph
            analysisSelectLocation($('#l1_analysis2s').val(), 2);
        }
    });
    $('#l2_analysis3s').change(function() {
        // Could be simplified, but then harder to migrate to L4s later
        for (var l=3; l <= 3; l++) {
            $('#l' + l + '_analysis3').hide().val('');
        }
        var id = this.value;
        if (id) {
            $('#lx_analysis3_throbber').removeClass('hidden').show();
            var h = hdata[$('#l0_analysis3s').val()];
            // Clear the old L3 values
            $('#l3_analysis3s').html('<option value="" selected="selected" class="none">Choose ' + h.l3 + '</option>');
            // Populate the L3
            if (typeof vdata[id].i === 'undefined') {
                // We don't have this vdata, so read it
                readHierarchy(id, 2, 3);
            } else {
                lx_select(id, 2, 3);
            }
        } else {
            // Update line on Graph
            analysisSelectLocation($('#l1_analysis3s').val(), 3);
        }
    });
    // L3
    $('#l3_analysis1s').change(function() {
        // Update line on Graph
        analysisSelectLocation(this.value, 1);
    });
    $('#l3_analysis2s').change(function() {
        // Update line on Graph
        analysisSelectLocation(this.value, 2);
    });
    $('#l3_analysis3s').change(function() {
        // Update line on Graph
        analysisSelectLocation(this.value, 3);
    });
    // L4

    // Style
    updateSelectMenus(false);
    var selected = $('#analysisControl2 select, #analysisControl3 select');
    try {
        selected.selectmenu('destroy');
    } catch(err) {}
    selected.selectmenu({
        style: 'popup',
        maxHeight: 280,
        width: 165,
        menuWidth: 165
    });
    selected = $('#analysisIndicator');
    try {
        selected.selectmenu('destroy');
    } catch(err) {}
    selected.selectmenu({
        style: 'popup',
        maxHeight: 120,
        width: 145,
        menuWidth: 145
    });

    // Add CSS classes for font smoothing
    // @ToDo: Are these useful without the fancy font?
    TypeHelpers.insertClasses();

    // Click events
    // Chrome frame
    $('.closechromeframe').click(function() { $('.chromeframe').hide(); });
    // Breadcrumbs
    $('#globalBreadCrumb').click(function() { globalView(); });
    // Drawer
    $('#show-hide').click(function() { drawerSlide(); });
    $('#risingTab').click(function() { drawerSlide(); });
    $('#newRegion').click(function() { goToRegion(); });
    $('#analysisLink').click(function() { analysisView(); });
    $('#analysisIndicator').change(function() { toggleAnalysis(); });
    $('#backToMap').click(function() { hideAnalysis(); });
    $('#analysisReset1').click(function() { analysisReset(1); });
    $('#analysisReset2').click(function() { analysisReset(2); });
    $('#analysisReset3').click(function() { analysisReset(3); });
    // Calculations info box
    $('.calculationLink').click(function() {
        $('#lightbox, #calculationView').fadeIn(300);
    });
    $('#calculationView .closePanel').click(function() {
        $('#lightbox, #calculationView').fadeOut(300);
    });

    // Close sections when lightbox surrounding area or X in upper-right corner is clicked
    $('#lightbox').click(function() {
        $('#lightbox, #reportsSection, #calculationView, #photoPanel, #submitDataSection').fadeOut(300);
    });
    $('#reportsSection .closePanel').click(function() {
        $('#lightbox, #reportsSection').fadeOut(300);
    });
    $('#submitDataSection .closePanel').click(function() {
        $('#submitDataContent').animate({
            'scrollTop': 0
        }, 100);
        $('#lightbox, #submitDataSection').fadeOut(300);
    });

    // Hover Events
    $('#dataTopBar').hover(function() {
        $('#dataTopBar img').css('background-color', '#f7941d');
        $('#dataTopBar img').attr('src', S3.Ap.concat('/static/themes/Vulnerability/img/dropdownArrowOverPng8.png'));
        $('#dataOptions').fadeIn(150);
        $('#defaultDataLink').css('color', '#c47a21');
    },
    function() {
        $('#dataTopBar img').css('background-color', 'transparent');
        $('#dataTopBar img').attr('src', S3.Ap.concat('/static/themes/Vulnerability/img/dropdownArrowPng8.png'));
        $('#dataOptions').fadeOut(150);
        $('#defaultDataLink').css('color', '#f7941d');
    });
    $('#reportsTopBar').hover(function() {
        $('#reportsTopBar img').css('background-color', '#f7941d');
        $('#reportsTopBar img').attr('src', S3.Ap.concat('/static/themes/Vulnerability/img/dropdownArrowOverPng8.png'));
        $('#reportsOptions').fadeIn(150);
        $('#defaultReportsLink').css('color', '#c47a21');
    },
    function() {
        $('#reportsTopBar img').css('background-color', 'transparent');
        $('#reportsTopBar img').attr('src', S3.Ap.concat('/static/themes/Vulnerability/img/dropdownArrowPng8.png'));
        $('#reportsOptions').fadeOut(150);
        $('#defaultReportsLink').css('color', '#f7941d');
    });
    // Indicators
    $('.listText').hover( function() {
        $(this).siblings('.popup').show();
    }, function() {
        $(this).siblings('.popup').hide();
    });
    $('#subGeo, .currentQuality').hover(function() {
        // Show popup with sub-geography if user hovers for .2 second
        var tempPopupDivVar = $(this).find('.popup');
        $(tempPopupDivVar).data('timeout', setTimeout(function() {
            showSubGeo(tempPopupDivVar, 200);
        }, 200));
    }, function() {
        // Cancel popup if user moves mouse before .2 second passes
        var tempPopupDivVar = $(this).find('.popup');
        hideSubGeo(tempPopupDivVar, 200);
        clearTimeout($(tempPopupDivVar).data('timeout'));
    });
});

// function to open/close sub-geography popup
function showSubGeo(popup, fadeSpeed) {
    if (typeof activeWindow !== 'undefined') {
        clearTimeout(activeWindow.data('timeout'));
        activeWindow.fadeOut(fadeSpeed);
    }
    popup.fadeIn(fadeSpeed);
    activeWindow = popup;
    //subGeoShowing = true;
}
function hideSubGeo(popup, fadeSpeed) {
    popup.fadeOut(fadeSpeed);
    //subGeoShowing = false;
}

function readHierarchy(id, level, analysis) {
    $.ajax({
        'url': S3.Ap.concat('/vulnerability/vdata/' + id),
        'dataType': 'script'
    }).done(function(data) {
        // Copy the vdata elements across
        for (var prop in n) {
            vdata[prop] = n[prop];
        }
        // Clear the memory
        n = null;
        lx_select(id, level, analysis);
    }).fail(function(request, status, error) {
        if (error == 'UNAUTHORIZED') {
            msg = i18n.gis_requires_login;
        } else {
            msg = request.responseText;
        }
    });
}

function lx_select(id, level, analysis) {
    // Hierarchical dropdown has been selected
    if (level === 0) {
        if (analysis) {
            // Set Value (to lookup labels later)
            $('#l' + level + '_analysis' + analysis + 's').val(id);
        } else {
            // Set Value (to lookup labels later)
            $('#l0_select, #l0_reports, #l0_datas, #l0_analysis1s').val(id);
            // Set Labels
            var h = hdata[id];
            $('#l1 label, #l1_report label, #l1_data label').html(h.l1.toUpperCase() + ':');
            $('#l2 label, #l2_report label, #l2_data label').html(h.l2.toUpperCase() + ':');
            $('#l3 label, #l3_report label, #l3_data label').html(h.l3.toUpperCase() + ':');
            //$('#l4 label, #l4_report label, #l4_data label').html(h.l4.toUpperCase() + ':');
        }
    }
    level = level + 1;
    var l;
    if (analysis) {
        $('#lx_analysis' + analysis + '_throbber').hide();
        $('#l' + level + '_analysis' + analysis).show();
        for (l=level + 1; l < 4; l++) {
            $('#l' + l + '_analysis' + analysis).hide().val('');
        }
    } else {
        $('#lx_select_throbber, #lx_report_throbber, #lx_data_throbber').hide();
        $('#l' + level + ', #l' + level + '_report, #l' + level + '_data, #l' + level + '_analysis1').show();
        for (l=level + 1; l < 4; l++) {
            $('#l' + l + ', #l' + l + '_report, #l' + l + '_data, #l' + l + '_analysis1').hide();
            $('#l' + l + '_select, #l' + l + '_reports, #l' + l + '_datas, #l' + l + '_analysis1s').val('');
        }
    }
    var values = [];
    var v;
    for (var prop in vdata) {
        v = vdata[prop];
        if (v['f'] == id) {
            v['id'] = prop;
            values.push(v);
        }
    }
    values.sort(nameSort);
    var res, option;
    for (var i=0; i < values.length; i++) {
        v = values[i];
        res = resilienceClass(v['r']);
        option = '<option value="' + v['id'] + '" class="' + res + '">' + v['n'] + '</option>';
        if (analysis) {
            $('#l' + level + '_analysis' + analysis + 's').append(option);
        } else {
            $('#l' + level + '_select, #l' + level + '_reports, #l' + level + '_datas, #l' + level + '_analysis1s').append(option);
        }
    }

    // Update Select Menus
    updateSelectMenus(analysis);

    // Update Analysis Graph
    if (analysis) {
        analysisSelectLocation(id, analysis);
    }
}

function updateL1Menus() {
    // Update L1 Hierarchical Location Selectors
    // Called from v_select_region
    $.ajax({
        'url': S3.Ap.concat('/vulnerability/vdata/' + current_l0),
        'async': true,
        'dataType': 'script'
    }).done(function(data) {
        var prop, v;
        // Copy the vdata elements across
        for (prop in n) {
            if (!vdata.hasOwnProperty(prop)) {
                vdata[prop] = n[prop];
            }
        }
        // Clear the memory
        n = null;

        // Update the options for the Hierarchical Location Selectors
        var values = [];
        for (prop in vdata) {
            v = vdata[prop];
            if (v['f'] == current_l0) {
                v['id'] = prop;
                values.push(v);
            }
        }
        values.sort(nameSort);
        var res, option;
        $('#l1_select, #l1_reports, #l1_datas, #l1_analysis1s').html('');
        for (var i=0; i < values.length; i++) {
            v = values[i];
            res = resilienceClass(v['r']);
            option = '<option value="' + v['id'] + '" class="' + res + '">' + v['n'] + '</option>';
            $('#l1_select, #l1_reports, #l1_datas, #l1_analysis1s').append(option);
        }
        $('#l1_select, #l1_reports, #l1_datas, #l1_analysis1s').val(current_l1);
        // Update Select Menus
        updateSelectMenus(false);
    }).fail(function(request, status, error) {
        if (error == 'UNAUTHORIZED') {
            msg = i18n.gis_requires_login;
        } else {
            msg = request.responseText;
        }
        console.log(msg);
    });
}

function updateSelectMenus(analysis) {
    if (analysis) {
        var selected = $('#analysisControl' + analysis + ' select');
        try {
            selected.selectmenu('destroy');
        } catch(err) {}
        selected.selectmenu({
            style: 'popup',
            maxHeight: 280,
            width: 165,
            menuWidth: 165
        });
    } else {
        // Drawer SelectMenu
        var selected = $('#browseOtherRegions select');
        try {
            selected.selectmenu('destroy');
        } catch(err) {}
        selected.selectmenu({
            style: 'popup',
            maxHeight: 280,
            width: 160,
            menuWidth: 160,
            icons: [
                {find: '.one'},
                {find: '.two'},
                {find: '.three'},
                {find: '.four'},
                {find: '.five'}
            ]
        });

        // Reports & Submit Data SelectMenus
        selected = $('.locationFilters select');
        try {
            selected.selectmenu('destroy');
        } catch(err) {}
        selected.selectmenu({
            style: 'popup',
            maxHeight: 280,
            width: 160,
            menuWidth: 160,
            icons: [
                {find: '.one'},
                {find: '.two'},
                {find: '.three'},
                {find: '.four'},
                {find: '.five'}
            ]
        });

        // Chart Switcher SelectMenu
        selected = $('#chartSwitcher');
        try {
            selected.selectmenu('destroy');
        } catch(err) {}
        selected.selectmenu({
            style: 'popup',
            maxHeight: 280,
            width: 125,
            menuWidth: 125
        });

        // Analysis SelectMenu
        selected = $('#analysisControl1 select');
        try {
            selected.selectmenu('destroy');
        } catch(err) {}
        selected.selectmenu({
            style: 'popup',
            maxHeight: 280,
            width: 165,
            menuWidth: 165
        });
    }
}

/* Map */
function showMap() {
    OpenLayers.ImgPath = S3.Ap.concat('/static/img/gis/openlayers/');
    proj4326 = new OpenLayers.Projection('EPSG:4326');

    // Basic Map
    map = new OpenLayers.Map('map', {
                                    // Use Manual stylesheet download (means can be done in HEAD to not delay pageload)
                                    theme: null
                                });
    // Base Layer
    //var baseLayer = new OpenLayers.Layer.OSM('OpenStreetMap',
    //        ['http://otile1.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.png',
    //         'http://otile2.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.png',
    //         'http://otile2.mqcdn.com/tiles/1.0.0/osm/${z}/${x}/${y}.png'],
    //         {attribution: 'Tiles Courtesy of <a href="http://open.mapquest.co.uk/" target="_blank">MapQuest</a> <img src="http://developer.mapquest.com/content/osm/mq_logo.png" border="0">'}
    //        );
    var baseLayer = new OpenLayers.Layer.WMS(
        'VMap0',
        'http://vmap0.tiles.osgeo.org/wms/vmap0',
        {layers: 'basic'},
        {wrapDateLine: true}
    );
    map.addLayer(baseLayer);

    // Pan Zoom Bar
    // Draw below the mapKey & 25px from each border
    OpenLayers.Control.PanZoom.X = 25;
    OpenLayers.Control.PanZoom.Y = 65;
    var panZoomBar = new OpenLayers.Control.PanZoomBar();
    map.addControl(panZoomBar);

    parser = new OpenLayers.Format.GeoJSON({
            //'internalProjection': map.getProjectionObject(),
            //'externalProjection': proj4326
        });

    // Resilience layer
    var style = {
        fillColor: '${fill}',
        fillOpacity: '${fillOpacity}',
        strokeColor: '#ffffff',
        strokeWidth: '${strokeWidth}',
        strokeOpacity: 1,
        graphicWidth: 14,
        graphicHeight: 14,
        graphicXOffset: -7,
        graphicYOffset: -14,
        graphicZIndex: '${zIndex}',
        graphicOpacity: 1,
        externalGraphic: '${externalGraphic}'
    };
    var style_options = {
        context: {
            fill: function(feature) {
                var color = colors[feature.attributes.r];
                return color;
            },
            fillOpacity: function(feature) {
                if (feature.attributes.outline) {
                    return 0.1;
                } else {
                    return 0.5;
                }
            },
            strokeWidth: function(feature) {
                if (feature.attributes.outline) {
                    return 2;
                } else {
                    return 1;
                }
            },
            zIndex: function(feature) {
                // Base zIndex
                var zIndex = feature.attributes.l;
                if (feature.geometry.getArea() === 0.0) {
                    // Marker
                    zIndex = zIndex + 10;
                } else if (feature.attributes.outline) {
                    zIndex = zIndex - 1;
                }
                return zIndex;
            },
            externalGraphic: function(feature) {
                if (feature.geometry.getArea() === 0.0) {
                    var resilience = feature.attributes.r;
                    var icon;
                    if ( resilience == 5 ) {
                        icon = '/static/themes/Vulnerability/img/rating5.png';
                    } else if ( resilience == 4 ) {
                        icon = '/static/themes/Vulnerability/img/rating4.png';
                    } else if ( resilience == 3 ) {
                        icon = '/static/themes/Vulnerability/img/rating3.png';
                    } else if ( resilience == 2 ) {
                        icon = '/static/themes/Vulnerability/img/rating2.png';
                    } else if ( resilience == 1 ) {
                        icon = '/static/themes/Vulnerability/img/rating1.png';
                    } else {
                        return '';
                    }
                    return S3.Ap.concat(icon);
                } else {
                    return '';
                }
            }
        }
    };
    var resilienceStyle = new OpenLayers.Style(
        style,
        style_options
    );
    var resilienceStyleMap = new OpenLayers.StyleMap({
        'default': resilienceStyle,
        'select': {
            fillOpacity: 1
        }
    });
    var strategy = new OpenLayers.Strategy.Fixed();
    //var strategy = new OpenLayers.Strategy.Grid();
    //var protocol = new OpenLayers.Protocol.HTTP({
            //url: "http://127.0.0.1:8080/countries/${z}/${x}/${y}.geojson",
    //        url: S3.Ap.concat("/static/cache/countries.geojson"),
    //        format: parser
    //    });
    // Empty dummy
    var protocol = new OpenLayers.Protocol({});
    resilienceLayer = new OpenLayers.Layer.Vector(
        'Resilience', {
            strategies: [strategy],
            protocol: protocol,
            styleMap: resilienceStyleMap,
            rendererOptions: {zIndexing: true}
        }
    );

    // Population Density layer (2010)
    populationLayer = new OpenLayers.Layer.WMS(
        'Population Density',
        'http://rmsgeo.aidiq.com/geoserver/gwc/service/wms',
        {layers: 'ifrc:populationDensity'},
        {wrapDateLine: true,
         isBaseLayer: false
         }
    );
    populationLayer.params.STYLES = 'populationDensityGrey';
    populationLayer.opacity = 0.8;

    // Volunteers layer
    var vol_style = {
        graphicWidth: '${graphicWidth}',
        graphicHeight: '${graphicHeight}',
        graphicXOffset: '${graphicXOffset}',
        graphicYOffset: '${graphicYOffset}',
        externalGraphic: '${externalGraphic}'
    };
    var vol_style_options = {
        context: {
            graphicWidth: function(feature) {
            	var pix;
                if (feature.cluster) {
                    // Stacked Icon
                    pix = 26;
                } else {
                    pix = 15;
                }
                return pix;
            },
            graphicHeight: function(feature) {
            	var pix;
                if (feature.cluster) {
                    // Stacked Icon
                    pix = 44;
                } else {
                    pix = 32;
                }
                return pix;
            },
            graphicXOffset: function(feature) {
            	var pix;
                // -marker_width / 2
                if (feature.cluster) {
                    // Stacked Icon
                    pix = -13;
                } else {
                    pix = -7;
                }
                return pix;
            },
            graphicYOffset: function(feature) {
            	var pix;
                // -(marker_height + offset for resilience marker)
                if (feature.cluster) {
                    // Stacked Icon
                    pix = -58;
                } else {
                    pix = -46;
                }
                return pix;
            },
            externalGraphic: function(feature) {
            	var icon;
                if (feature.cluster) {
                    // Stacked Icon
                    icon = '/static/themes/Vulnerability/img/volunteer.png';
                } else {
                    icon = '/static/themes/Vulnerability/img/volunteerIconOnPng8.png';
                }
                return S3.Ap.concat(icon);
            }
        }
    };
    var volStyle = new OpenLayers.Style(
        vol_style,
        vol_style_options
    );
    var volStyleMap = new OpenLayers.StyleMap({
        'default': volStyle
    });
    volunteerLayer = new OpenLayers.Layer.Vector(
        'Volunteers',
        {strategies: [
                new OpenLayers.Strategy.BBOX({
                    ratio: 1.5
                }),
                new OpenLayers.Strategy.Cluster({
                    distance: 20,
                    threshold: 2
                })
            ],
        styleMap: volStyleMap,
        protocol: new OpenLayers.Protocol.HTTP({
            url: S3.Ap.concat('/vol/volunteer.geojson?components=None&maxdepth=0&references=location_id&fields=name&attr=person_id,phone,email&human_resource.status=1'), //&track=1
            format: new OpenLayers.Format.GeoJSON()
            })
        }
    );

    // Hand-drawn Maps layer
    var map_style = {
        graphicWidth: '${graphicWidth}',
        graphicHeight: '${graphicHeight}',
        graphicXOffset: '${graphicXOffset}',
        graphicYOffset: '${graphicYOffset}',
        graphicZIndex: 20,
        externalGraphic: '${externalGraphic}'
    };
    var map_style_options = {
        context: {
            graphicWidth: function(feature) {
            	var pix;
                if (feature.cluster) {
                    // Stacked Icon
                    pix = 46;
                } else {
                    pix = 18;
                }
                return pix;
            },
            graphicHeight: function(feature) {
            	var pix;
                if (feature.cluster) {
                    // Stacked Icon
                    pix = 61;
                } else {
                    pix = 31;
                }
                return pix;
            },
            graphicXOffset: function(feature) {
            	var pix;
                // -marker_width / 2
                if (feature.cluster) {
                    // Stacked Icon
                    pix = -23;
                } else {
                    pix = -9;
                }
                return pix;
            },
            graphicYOffset: function(feature) {
            	var pix;
                // -(marker_height + offset for resilience marker)
                if (feature.cluster) {
                    // Stacked Icon
                    pix = -75;
                } else {
                    pix = -45;
                }
                return pix;
            },
            externalGraphic: function(feature) {
            	var icon;
                if (feature.cluster) {
                    // Stacked Icon
                    icon = '/static/themes/Vulnerability/img/map.png';
                } else {
                    icon = '/static/themes/Vulnerability/img/mapIconOnPng8.png';
                }
                return S3.Ap.concat(icon);
            }
        }
    };
    var mapStyle = new OpenLayers.Style(
        map_style,
        map_style_options
    );
    var mapStyleMap = new OpenLayers.StyleMap({
        'default': mapStyle
    });
    mapLayer = new OpenLayers.Layer.Vector(
        'Maps',
        {strategies: [
                new OpenLayers.Strategy.BBOX({
                    ratio: 1.5
                }),
                new OpenLayers.Strategy.Cluster({
                    distance: 20,
                    threshold: 2
                })
            ],
        styleMap: mapStyleMap,
        protocol: new OpenLayers.Protocol.HTTP({
            url: S3.Ap.concat('/vulnerability/handdrawn.geojson?components=None&maxdepth=0&references=location_id&fields=name'),
            format: new OpenLayers.Format.GeoJSON()
            }),
        rendererOptions: {zIndexing: true}
        }
    );

    // Popup control
    popupControl = new OpenLayers.Control.SelectFeatureDouble(
        [resilienceLayer, volunteerLayer], {
            toggle: true
        }
    );
    popupControl.handlers.feature.callbacks.dblclick = function(feature) {
        if (feature.layer.name == 'Resilience') {
            this.handlers.feature.stopDouble = true;
            var id = feature.attributes.id;
            if (vdata[id].q == undefined) {
                // We don't have this vdata, so read it now rather than per-subFeature
                $.ajax({
                    'url': S3.Ap.concat('/vulnerability/vdata/' + id),
                    'async': false,
                    'dataType': 'script'
                }).done(function(data) {
                    // Copy the vdata elements across
                    for (var prop in n) {
                        vdata[prop] = n[prop];
                    }
                    // Clear the memory
                    n = null;
                    // Proceed: Select the region
                    v_select_region(feature.attributes.l, id);
                }).fail(function(request, status, error) {
                    if (error == 'UNAUTHORIZED') {
                        msg = i18n.gis_requires_login;
                    } else {
                        msg = request.responseText;
                    }
                    console.log(msg);
                });
            } else {
                // We have the data already: proceed
                v_select_region(feature.attributes.l, id);
            }
        } else {
            // Volunteer layer or Hand-drawn Maps layer
            this.handlers.feature.stopDouble = false;
        }
    };

    // PopupControl needs to be defined
    map.addLayer(resilienceLayer);
    resilienceLayer.events.on({
        'beforefeatureadded': addAttributes,
        'featureselected': onResilienceFeatureSelect,
        'featureunselected': onFeatureUnselect
    });
    enableResilienceLayer();

    // Open at the correct level
    if (start === '') {
        globalView();
    } else {
        v_select_region(0, start);
    }

    map.addControl(popupControl);
    popupControl.activate();

    // Listen for Disable/Enable events
    $('#resilienceCheck').change(function() {
        if ($('#resilienceCheck').is(':checked')) {
            enableResilienceLayer();
        } else {
            disableResilienceLayer();
        }
    });
    $('#populationCheck').change(function() {
        if ($('#populationCheck').is(':checked')) {
            map.addLayer(populationLayer);
        } else {
            map.removeLayer(populationLayer);
        }
    });
    $('#iconsCheck').change(function() {
        if ($('#iconsCheck').is(':checked')) {
            enableVolunteerLayer();
            enableMapLayer();
        } else {
            disableVolunteerLayer();
            map.removeLayer(mapLayer);
        }
    });

    // Disable PopulationLayer at High Zooms
    map.events.on({
        'zoomend': function(event) {
            var zoom = map.getZoom();
            var populationEnabled = map.getLayersByName('Population Density').length;
            if (zoom > 9) {
                $('#populationKey label').css('color', '#ccc');
                $('#populationCheck').hide();
                if (populationEnabled) {
                    map.removeLayer(populationLayer);
                }
            } else {
                $('#populationKey label').css('color', '');
                $('#populationCheck').show();
                if (($('#populationCheck').is(':checked')) && (!populationEnabled)) {
                    map.addLayer(populationLayer);
                }
            }
        }
    });
}

/* Map support functions */
function enableResilienceLayer() {
    // Load the features
    $.ajax({
        'url': S3.Ap.concat('/static/cache/countries.geojson'),
        'async': false,
        'dataType': 'json'
    }).done(function(data) {
        var features = parser.read(data);
        var newfeatures = [];
        var current_projection = map.getProjectionObject();
        for (var prop in features) {
            // 'remove' is a prop
            try {
                features[prop].geometry.transform(proj4326,
                                                  current_projection);
                newfeatures.push(features[prop]);
            } catch(err) {}
        }
        resilienceLayer.addFeatures(newfeatures);
    }).fail(function(request, status, error) {
        if (error == 'UNAUTHORIZED') {
            msg = i18n.gis_requires_login;
        } else {
            msg = request.responseText;
        }
        console.log(msg);
    });
    if (current_l0) {
        $.ajax({
            'url': S3.Ap.concat('/static/cache/1_' + current_l0 + '.geojson'),
            'async': false,
            'dataType': 'json'
        }).done(function(data) {
            var features = parser.read(data);
            var newfeatures = [];
            var current_projection = map.getProjectionObject();
            for (var prop in features) {
                // 'remove' is a prop
                try {
                    features[prop].geometry.transform(proj4326,
                                                      current_projection);
                    newfeatures.push(features[prop]);
                } catch(err) {}
            }
            resilienceLayer.addFeatures(newfeatures);
        }).fail(function(request, status, error) {
            if (error == 'UNAUTHORIZED') {
                msg = i18n.gis_requires_login;
            } else {
                msg = request.responseText;
            }
            console.log(msg);
        });
    }
    if (current_l1) {
        $.ajax({
            'url': S3.Ap.concat('/static/cache/2_' + current_l1 + '.geojson'),
            'async': false,
            'dataType': 'json'
        }).done(function(data) {
            var features = parser.read(data);
            var newfeatures = [];
            var current_projection = map.getProjectionObject();
            for (var prop in features) {
                // 'remove' is a prop
                try {
                    features[prop].geometry.transform(proj4326,
                                                      current_projection);
                    newfeatures.push(features[prop]);
                } catch(err) {}
            }
            resilienceLayer.addFeatures(newfeatures);
        }).fail(function(request, status, error) {
            if (error == 'UNAUTHORIZED') {
                msg = i18n.gis_requires_login;
            } else {
                msg = request.responseText;
            }
            console.log(msg);
        });
    }
    if (current_l2) {
        $.ajax({
            'url': S3.Ap.concat('/static/cache/3_' + current_l2 + '.geojson'),
            'async': false,
            'dataType': 'json'
        }).done(function(data) {
            var features = parser.read(data);
            var newfeatures = [];
            var current_projection = map.getProjectionObject();
            for (var prop in features) {
                // 'remove' is a prop
                try {
                    features[prop].geometry.transform(proj4326,
                                                      current_projection);
                    newfeatures.push(features[prop]);
                } catch(err) {}
            }
            resilienceLayer.addFeatures(newfeatures);
        }).fail(function(request, status, error) {
            if (error == 'UNAUTHORIZED') {
                msg = i18n.gis_requires_login;
            } else {
                msg = request.responseText;
            }
            console.log(msg);
        });
    }
    //if (current_l3) {
    //if (current_l4) {
    popupControl.unselectAll();
}
function disableResilienceLayer() {
    resilienceLayer.removeAllFeatures();
}

function enableVolunteerLayer() {
    map.addLayer(volunteerLayer);
    volunteerLayer.events.on({
        'featureselected': onVolunteerFeatureSelect,
        'featureunselected': onFeatureUnselect
    });
    // Move this layer to the top
    map.raiseLayer(volunteerLayer, 2);
}

function disableVolunteerLayer() {
    volunteerLayer.removeAllFeatures();
    map.removeLayer(volunteerLayer);
}

function enableMapLayer() {
    map.addLayer(mapLayer);
    //mapLayer.events.on({
    //    'featureselected': onMapFeatureSelect,
    //    'featureunselected': onFeatureUnselect
    //});
    // Move this layer above resilienceLayer
    //map.raiseLayer(mapLayer, 2);
}

function addAttributes(event) {
    var f = event.feature;
    var attr = f.attributes;
    var id = attr.id;
    if (typeof vdata[id] === 'undefined') {
        // We don't have this vdata, so read it
        $.ajax({
            'url': S3.Ap.concat('/vulnerability/vdata/' + id),
            'async': false,
            'dataType': 'script'
        }).done(function(data) {
            // Copy the vdata elements across
            for (var prop in n) {
                vdata[prop] = n[prop];
            }
            // Clear the memory
            n = null;
        }).fail(function(request, status, error) {
            if (error == 'UNAUTHORIZED') {
                msg = i18n.gis_requires_login;
            } else {
                msg = request.responseText;
            }
            console.log(msg);
        });
    }
    var v = vdata[id];
    var l = v.l;
    var r = v.r;
    attr.l = l;
    attr.r = r;
    if (l > 1) {
        // Add a Point at the Centroid
        var g = f.geometry;
        if (g.getArea() !== 0.0) {
            // Not the Point we just added
            try {
                var p = new OpenLayers.Feature.Vector(g.getCentroid(true), {
                                                          id: parseInt(id, 10),
                                                          l: l,
                                                          r: r
                                                        });
                resilienceLayer.addFeatures([p]);
            } catch(err) {}
        }
    }
}

function onFeatureUnselect(event) {
    var feature = event.feature;
    if (feature.popup) {
        $('.ui-selectmenu-menu').removeClass('ui-selectmenu-open');
        map.removePopup(feature.popup);
        feature.popup.destroy();
        delete feature.popup;
    }
}

function onResilienceFeatureSelect(event) {
    if (drawerOpen) {
        // Close it
        drawerSlide();
    }
    var feature = event.feature;
    // Center the feature
    var centerPoint = feature.geometry.getBounds().getCenterLonLat();
    map.setCenter(centerPoint);

    var id = feature.attributes.id;
    var level = feature.attributes.l;
    var windowQualityRatings = "\
    <h3>" + i18n.data_quality.toUpperCase() + ":</h3>\
     <div class='windowQualityRatings'>\
        <div class='poor'>" + i18n.poor.toUpperCase() +"\
            <div class='popup'>\
                <div class='popupContent'>\
                    <h3>" + i18n.poor.toUpperCase() +"</h3>\
                    <p>0&ndash;25% " + i18n.of_total_data_reported + ".</p>\
                </div>\
                <div class='popupBottom'></div>\
            </div>\
        </div> | \
        <div class='fair'>" + i18n.fair.toUpperCase() +"\
            <div class='popup'>\
                <div class='popupContent'>\
                    <h3>" + i18n.fair.toUpperCase() +"</h3>\
                    <p>25&ndash;50% " + i18n.of_total_data_reported + ".</p>\
                </div>\
                <div class='popupBottom'></div>\
            </div>\
        </div> | \
        <div class='moderate'>" + i18n.moderate.toUpperCase() +"\
            <div class='popup'>\
                <div class='popupContent'>\
                    <h3>" + i18n.moderate.toUpperCase() +"</h3>\
                    <p>50&ndash;75% " + i18n.of_total_data_reported + ".</p>\
                </div>\
                <div class='popupBottom'></div>\
            </div>\
        </div> | \
        <div class='strong'>" + i18n.strong.toUpperCase() +"\
            <div class='popup'>\
                <div class='popupContent'>\
                    <h3>" + i18n.strong.toUpperCase() +"</h3>\
                    <p>75&ndash;100% " + i18n.of_total_data_reported + ".</p>\
                </div>\
                <div class='popupBottom'></div>\
            </div>\
        </div>\
    </div>";
    var iclass = '';
    var v = vdata[id];
    var h, type, typec, subtype, communeName, subGeoSelect;
    switch(level) {
        case 0:
            h = hdata[id];
            type = i18n.country;
            typec = i18n.country.toUpperCase();
            subtype = h.l1.toUpperCase();
            communeName = h.l3;
            // @ToDo: Better i18n
            subGeoSelect = "\
            <h3>" + subtype + 'S ' + i18n.in_this.toUpperCase() + ' ' + typec + ":</h3>\
            <select class='subGeoSelect hidden'></select>\
            <span id='subGeo_throbber' class='throbber'></span>\
			<a id='goToSubRegion' class='goToSubRegion'>" + i18n.go_to_the.toUpperCase() + ' ' + subtype + " <span class='arrow'>&rarr;</span></a>";
			break;
        case 1:
            h = hdata[current_l0];
            type = h.l1;
            typec = type.toUpperCase();
            subtype = h.l2.toUpperCase();
            communeName = h.l3;
            // @ToDo: Better i18n
            subGeoSelect = "\
            <h3>" + subtype + 'S ' + i18n.in_this.toUpperCase() + ' ' + typec + ":</h3>\
            <select class='subGeoSelect hidden'></select>\
            <span id='subGeo_throbber' class='throbber'></span>\
			<a id='goToSubRegion' class='goToSubRegion'>" + i18n.go_to_the.toUpperCase() + ' ' + subtype + " <span class='arrow'>&rarr;</span></a>";
			break;
        case 2:
            h = hdata[current_l0];
            type = h.l2;
            typec = type.toUpperCase();
            subtype = h.l3.toUpperCase();
            communeName = h.l3;
            // @ToDo: Better i18n
            subGeoSelect = "\
            <h3>" + subtype + 'S ' + i18n.in_this.toUpperCase() + ' ' + typec + ":</h3>\
            <select class='subGeoSelect hidden'></select>\
            <span id='subGeo_throbber' class='throbber'></span>\
			<a id='goToSubRegion' class='goToSubRegion'>" + i18n.go_to_the.toUpperCase() + ' ' + subtype + " <span class='arrow'>&rarr;</span></a>";
			break;
        case 3:
            h = hdata[current_l0];
            type = h.l3;
            typec = type.toUpperCase();
            //var subtype = h.l4.toUpperCase();
            //communeName;
            subGeoSelect = '';
            windowQualityRatings = "<div class='lastCollected'></div>";
			iclass = ' communeWindow';
            break;
        //case 4:
        //    h = hdata[current_l0];
        //    type = h.l4;
        //    typec = type.toUpperCase();
        //    communeName;
        //    subGeoSelect = '';
        //    windowQualityRatings = "<div class='lastCollected'></div>";
		//    iclass = ' communeWindow';
        //	break;
    }
    var name = v.n;
    var resilience = v.r;
    if (resilience === 0) {
        resilience = '';
    }
    if (communeName) {
        windowQualityRatings += "<div class='subGeoCommunesReported'></div>";
    }

    var contents = "\
    <section class='infoWindow'>\
		<div class='infoWindowMain unselectable'>\
			<div id='subGeoIndicator'>" + resilience + "</div>\
			<h2 class='subGeoName'>" + name + "</h2>\
			<h2 class='subGeoType'>" + type + "</h2>\
			<a id='goToRegion' class='goToSubRegion'>" + i18n.go_to_the.toUpperCase() + " " + typec + " <span class='arrow'>&rarr;</span></a>\
			" + windowQualityRatings + "\
			<h3 id='population'>" + i18n.population.toUpperCase() + ": </h3>\
			" + subGeoSelect + "\
			<div class='infoWindowButtons'>\
				<div class='subGeoSubmitDataButton'>" + i18n.submit_data + "</div>\
				<div class='subGeoAnalysisButton'>" + i18n.analysis + "</div>\
				<div class='subGeoReportsButton'>" + i18n.reports + "</div>\
			</div>\
		</div>\
	</section>";

    var popup = new OpenLayers.Popup.FramedCloudLocation(
        id.toString(),
        centerPoint,
        new OpenLayers.Size(200, 200),
        contents,
        null,
        true,
        closePopups
    );
    feature.popup = popup;
    map.addPopup(popup);

    if ('p' in v) {
        // We already have the data
        fillPopup(v, level, id, popup, communeName);
    } else {
        // Read extra data for location
        // Load the Popup Details asynchronously
        $.ajax({
            'url': S3.Ap.concat('/vulnerability/vdata/' + id),
            'dataType': 'script'
        }).done(function(data) {
            // Copy the vdata elements across
            for (var prop in n) {
                vdata[prop] = n[prop];
            }
            // Clear the memory
            n = null;
            v = vdata[id];
            fillPopup(v, level, id, popup, communeName);
        }).fail(function(request, status, error) {
            if (error == 'UNAUTHORIZED') {
                msg = i18n.gis_requires_login;
            } else {
                msg = request.responseText;
            }
            $('#' + id + '_contentDiv').html(msg);
            popup.updateSize();
        });
    }
    // Set the CSS for the Indicator box
    if (resilience === '') {
        $('#subGeoIndicator').css('background-color', colors[0]);
    } else {
        $('#subGeoIndicator').css('background-color', colors[resilience]);
    }
    // Click handlers
    $('.subGeoSubmitDataButton').click(function() {
        $('#l' + level + '_datas').val(id);
        $('#l' + level + '_datas').change();
        showSubmitData('indicators');
    });
    $('.subGeoAnalysisButton').click(function() {
        $('#l' + level + '_analysis1s').val(id);
        $('#l' + level + '_analysis1s').change();
        analysisView();
    });
    $('.subGeoReportsButton').click(function() {
        v_select_region(level, id);
        $('#l' + level + '_reports').val(id);
        $('#lightbox, #reportsSection').fadeIn(300);
        filterReport();
    });
    // Allow the quality hover popups to overflow their container
    $('.olPopup').css('overflow', 'visible');
    $('.olPopup > div').css('overflow', 'visible');
}

function fillPopup(v, level, id, popup, communeName) {
    $('#subGeo_throbber').hide();
    $('.subGeoSelect').removeClass('hidden').show();
    // Fill the Popup with the extra data
    if (communeName) {
        // Add Communes info
        $('.subGeoCommunesReported').html(v.c + ' ' + i18n.out_of + ' ' + v.t + ' ' + communeName + 's ' + i18n.reported);
    } else {
        // Add Last collected info
        $('.windowQualityRatings').html(i18n.last_data_collected_on + ' ' + v.d + ' ' + i18n.by + ' ' + v.w);
    }
    // Add Population info
    var pop = v['p'];
    if (pop) {
        $('#population').html(i18n.population.toUpperCase() + ': ' + pop);
    }

    // Click Handler for Region Select
    $('#goToRegion').click(function() {
        $('#subGeo_throbber').show();
        v_select_region(level, id);
    });

    if (level == 3) {
        // Photos
        var m = v['m'];
        var length = m.length;
        if (length) {
            // m = [thumbnail, fullsize, name, created_by]
            var _m1 = m[0];
            var download = S3.Ap.concat('/default/download/');
            var thumbnail1 = download.concat(_m1[0]);
            var second;
            if (length > 1) {
                var _m2 = m[1];
                var thumbnail2 = download.concat(_m2[0]);
                second = "<img class='secondImage' src='" + thumbnail2 + "'/>";
            } else {
                second = '';
            }
            infoWindowImages = "\
            <div class='infoWindowImages'>\
                <img class='firstImage' src='" + thumbnail1 + "'/>\
                " + second + "\
            </div>";
            $('#population').after(infoWindowImages);
            $('.firstImage').click(function() {
                var name = _m1[2];
                var fullsize = download.concat(_m1[1]);
                $('.leftBar').append("<img class='activeImage' src='" + thumbnail1 + "' alt='" + name + "' index=0 />");
                $('.photoCaption a').attr('href', fullsize)
                                    .attr('alt', name);
                $('.photoDescription').html(name + ' ' + i18n.submitted_by + ' ' + _m1[3]);
                $('.photoPane > img').attr('src', fullsize)
                                     .attr('alt', name);
                for (var i=1; i < length; i++) {
                    var _m = m[i];
                    $('.leftBar').append("<img src='" + download.concat(_m[0]) + "' alt='" + _m[2] + "' index='" + i + "' />");
                }
                $('.leftBar img').click(function() {
                    $('.activeImage').removeClass('activeImage');
                    var attr = this.attributes;
                    for (var prop in attr) {
                        if (attr[prop].nodeName == 'index') {
                            var i = attr[prop].nodeValue;
                            $('.leftBar img[index="' + i + '"]').addClass('activeImage');
                        }
                    }
                    var _m = m[i];
                    var name = _m[2];
                    var fullsize = download.concat(_m[1]);
                    $('.photoCaption a').attr('href', fullsize)
                                        .attr('alt', name);
                    $('.photoDescription').html(name + ' ' + i18n.submitted_by + ' ' + _m[3]);
                    $('.photoPane > img').attr('src', fullsize)
                                         .attr('alt', name);
                    i++;
                    $('.photoNumber').html(i + ' ' + i18n.of + ' ' + length);
                });
                $('#lightbox, #photoPanel').fadeIn(300);
                $('.photoNumber').html('1 ' + i18n.of + ' ' + length);
                $('#photoPanel .closePanel').click(function() {
                    $('#lightbox, #photoPanel').fadeOut(300);
                    $('.leftBar').html('');
                });
            });
            $('.secondImage').click(function() {
                var name = _m2[2];
                var fullsize = download.concat(_m2[1]);
                $('.leftBar').append("<img src='" + thumbnail1 + "' alt='" + m[0][2] + "' index=0 />");
                $('.leftBar').append("<img class='activeImage' src='" + thumbnail2 + "' alt='" + name + "' index=1 />");
                $('.photoCaption a').attr('href', fullsize)
                                    .attr('alt', name);
                $('.photoDescription').html(name + ' ' + i18n.submitted_by + ' ' + _m2[3]);
                $('.photoPane > img').attr('src', fullsize)
                                     .attr('alt', name);
                for (var i=2; i < length; i++) {
                    var _m = m[i];
                    $('.leftBar').append("<img src='" + download.concat(_m[0]) + "' alt='" + _m[2] + "' index='" + i + "' />");
                }
                $('.leftBar img').click(function() {
                    $('.activeImage').removeClass('activeImage');
                    var attr = this.attributes;
                    for (var prop in attr) {
                        if (attr[prop].nodeName == 'index') {
                            var i = attr[prop].nodeValue;
                            $('.leftBar img[index="' + i + '"]').addClass('activeImage');
                        }
                    }
                    var _m = m[i];
                    var name = _m[2];
                    var fullsize = download.concat(_m[1]);
                    $('.photoCaption a').attr('href', fullsize)
                                        .attr('alt', name);
                    $('.photoDescription').html(name + ' ' + i18n.submitted_by + ' ' + _m[3]);
                    $('.photoPane > img').attr('src', fullsize)
                                         .attr('alt', name);
                    i++;
                    $('.photoNumber').html(i + ' ' + i18n.of + ' ' + length);
                });
                $('#lightbox, #photoPanel').fadeIn(300);
                $('.photoNumber').html('2 ' + i18n.of + ' ' + length);
                $('#photoPanel .closePanel').click(function() {
                    $('#lightbox, #photoPanel').fadeOut(300);
                    $('.leftBar').html('');
                });
            });
        }
    } else {
        // Select Quality
        switch(v['q']) {
             case 'p':
                $('.poor').addClass('currentQuality')
                          .hover(function() {
                    $(this).find('.popup').show();
                }, function() {
                    $(this).find('.popup').hide();
                });
                break;
             case 'f':
                $('.fair').addClass('currentQuality')
                          .hover(function() {
                    $(this).find('.popup').show();
                }, function() {
                    $(this).find('.popup').hide();
                });
                break;
             case 'm':
                $('.moderate').addClass('currentQuality')
                              .hover(function() {
                    $(this).find('.popup').show();
                }, function() {
                    $(this).find('.popup').hide();
                });
                break;
             case 's':
                $('.strong').addClass('currentQuality')
                            .hover(function() {
                    $(this).find('.popup').show();
                }, function() {
                    $(this).find('.popup').hide();
                });
                break;
        }

        // Populate SelectMenu
        var values = [];
        var x;
        for (var prop in vdata) {
            x = vdata[prop];
            if ((x['l'] == level + 1) && (x['f'] == id)) {
                x['id'] = prop;
                values.push(x);
            }
        }
        values.sort(nameSort);
        var res;
        for (var i=0; i < values.length; i++) {
            x = values[i];
            res = resilienceClass(x['r']);
            $('.subGeoSelect').append('<option value="' + x['id'] + '" class="' + res + '">' + x['n'] + '</option>');
        }
        // Style SelectMenu
        $('.subGeoSelect').selectmenu({
            style: 'popup',
            maxHeight: 280,
            width: 165,
            menuWidth: 165,
            icons: [
                {find: '.one'},
                {find: '.two'},
                {find: '.three'},
                {find: '.four'},
                {find: '.five'}
            ]
        });

        // Click Handler for SubRegion Select
        $('#goToSubRegion').click(function() {
            $('#subGeo_throbber').show();
            var id = $('.subGeoSelect').val();
            if (vdata[id].q == undefined) {
                // We don't have this vdata, so read it now rather than per-subFeature
                $.ajax({
                    'url': S3.Ap.concat('/vulnerability/vdata/' + id),
                    'async': false,
                    'dataType': 'script'
                }).done(function(data) {
                    // Copy the vdata elements across
                    for (var prop in n) {
                        vdata[prop] = n[prop];
                    }
                    // Clear the memory
                    n = null;
                    // Proceed: Select the region
                    v_select_region(level + 1, id);
                }).fail(function(request, status, error) {
                    if (error == 'UNAUTHORIZED') {
                        msg = i18n.gis_requires_login;
                    } else {
                        msg = request.responseText;
                    }
                    console.log(msg);
                });
            } else {
                // We have the data already: proceed
                v_select_region(level + 1, id);
            }
        });
    }

    popup.updateSize();
    // Resize when images are loaded
    //popup.registerImageListeners();
}

function onVolunteerFeatureSelect(event) {
    var feature = event.feature;
    var centerPoint = feature.geometry.getBounds().getCenterLonLat();
    var contents;
    if (feature.cluster) {
        // Cluster
        contents = '';
        for (var i = 0; i < feature.cluster.length; i++) {
            contents += feature.attributes.person_id + '<br/>';
        }
    } else {
        // Single Feature
        var attr = feature.attributes;
        contents = '<strong>' + attr.person_id + '</strong>';
        if (attr.phone) {
            contents += '<br/>' + attr.phone;
        }
        if (attr.email) {
            contents += '<br/><a href="mailto:' + attr.email + '">' + attr.email + '</a>';
        }
    }
    var html = "<section id='volPopup'>\
               " + contents + "\
                </section>";
    var popup = new OpenLayers.Popup.FramedCloudVolunteer(
        S3.uid(),
        centerPoint,
        new OpenLayers.Size(200, 200),
        html,
        null,
        true,
        closePopups
    );
    feature.popup = popup;
    map.addPopup(popup);
}

function closePopups(event) {
    // Close all Popups
    // Close orphaned Popups (e.g. from Refresh)
    while (map.popups.length) {
        map.removePopup(map.popups[0]);
    }
    // Close any open selectMenu
    $('.ui-selectmenu-menu').removeClass('ui-selectmenu-open');
}

function hideFeature(id) {
    var features = resilienceLayer.getFeaturesByAttribute('id', parseInt(id, 10));
    for (var prop in features) {
        // 'remove' is a prop
        try {
            var feature = features[prop];
            if (feature.geometry.getArea() === 0.0) {
                // Remove the Point
                feature.destroy();
            } else {
                // Restyle the Polygon to just thicker border with no fill
                feature.attributes.outline = 1;
                resilienceLayer.drawFeature(feature);
            }
        } catch(err) {}
    }
}

function showFeature(id) {
    if (id === null) {
        return;
    }
    var features = resilienceLayer.getFeaturesByAttribute('id', parseInt(id, 10));
    for (var prop in features) {
        // 'remove' is a prop
        try {
            var feature = features[prop];
            // Restyle the Polygon
            feature.attributes.outline = 0;
            resilienceLayer.drawFeature(feature);
            var l = attr.l;
            if (l > 1) {
                // Add a Point at the Centroid
                var attr = feature.attributes;
                var p = new OpenLayers.Feature.Vector(feature.geometry.getCentroid(true), {
                                                          id: parseInt(id, 10),
                                                          l: l,
                                                          r: attr.r
                                                        });
                resilienceLayer.addFeatures([p]);
            }
        } catch(err) {}
    }
}

function removeFeatures(level) {
    var feature;
    var features = [];
    for (var prop in resilienceLayer.features) {
        feature = resilienceLayer.features[prop];
        // 'remove' is a prop
        try {
            if (feature.attributes.l >= level) {
                // Don't destroy here or indices get altered!
                features.push(feature);
            }
        } catch(err) {}
    }
    resilienceLayer.destroyFeatures(features);
}

function globalView() {
    // Close Popups
    closePopups();

    if (drawerOpen) {
        // Close Drawer
        drawerSlide();
    }

    // Remove all Features > L0
    removeFeatures(1);

    // Zoom to full AP region
    //var current_projection = map.getProjectionObject();
    //var bottom_left = new OpenLayers.LonLat(80, -50).transform(
    //        proj4326,
    //        current_projection
    //    )
    //var top_right = new OpenLayers.LonLat(180, 50).transform(
    //        proj4326,
    //        current_projection
    //    )
    //var bounds = [bottom_left.lon, bottom_left.lat, top_right.lon, top_right.lat];
    //map.zoomToExtent(bounds);
    // Zoom to full globe
    map.zoomToMaxExtent();

    // Display the old L0 normally again
    showFeature(current_l0);

    // Tweak menu bars
    $('#l0_breadcrumb, #l1_breadcrumb, #l2_breadcrumb, #l3_breadcrumb').hide();
    //$('#l4_breadcrumb, #l5_breadcrumb').hide();
    $('#show-hide, #divider, #analysisLink, #indicator, #risingTab').hide();
    $('#indicator').hide();
    $('.geoName').html('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + i18n.select_country);
    $('.geoType').html('');
    $('.year').html('');
    $('#l0_select, #l0_reports, #l0_datas, #l0_analysis1s').val('');
    $('#l1_select, #l1_reports, #l1_datas, #l1_analysis1s').val('');
    $('#l2_select, #l2_reports, #l2_datas, #l2_analysis1s').val('');
    $('#l3_select, #l3_reports, #l3_datas, #l3_analysis1s').val('');
    //$('#l4_select, #l4_reports, #l4_datas, #l4_analysis1s').val('');
    //$('#l5_select, #l5_reports, #l5_datas, #l5_analysis1s').val('');
    $('#l1, #l1_report, #l1_data, #l1_analysis1').hide();
    $('#l2, #l2_report, #l2_data, #l2_analysis1').hide();
    $('#l3, #l3_report, #l3_data, #l3_analysis1').hide();
    //$('#l4, #l4_report, #l4_data, #l4_analysis1').hide();
    //$('#l5, #l5_report, #l5_data, #l5_analysis1').hide();
    markersOff();

    current_l0 = null;
    current_l1 = null;
    current_l2 = null;
    current_l3 = null;
    //current_l4 = null;
}

function v_select_region(level, id) {

    closePopups();
    var v = vdata[id];

    var h, l0_name, l1_name, l2_name, l3_name, type, features;
    switch(level) {
        case 0:
            if (current_l0 != id) {
                showFeature(current_l0);
                // Set
                current_l0 = id;
            }
            current_l1 = '';
            current_l2 = '';
            current_l3 = '';
            //current_l4 = '';
            //current_l5 = '';
            h = hdata[id];
            l0_name = v.n;
            $('#l1_breadcrumb, #l2_breadcrumb, #l3_breadcrumb').hide();
            //$('#l4_breadcrumb, #l5_breadcrumb').hide();
            $('#l0_breadcrumb').show().attr('href', 'javascript:v_select_region(0,' + id + ');');
            $('#l0_breadcrumb span').html(' &raquo; ' + l0_name);
            $('.geoName').html(l0_name);
            $('.geoType').html(i18n.country_in);
            $('#l0_select, #l0_reports, #l0_datas, #l0_analysis1s').val(id);
            $('#l1_select, #l1_reports, #l1_datas, #l1_analysis1s').val('');
            $('#l2_select, #l2_reports, #l2_datas, #l2_analysis1s').val('');
            $('#l3_select, #l3_reports, #l3_datas, #l3_analysis1s').val('');
            //$('#l4_select, #l4_reports, #l4_datas, #l4_analysis1s').val('');
            //$('#l5_select, #l5_reports, #l5_datas, #l5_analysis1s').val('');
            $('#l1, #l1_report, #l1_data, #l1_analysis1').show();
            $('#l2, #l2_report, #l2_data, #l2_analysis1').hide();
            $('#l3, #l3_report, #l3_data, #l3_analysis1').hide();
            //$('#l4, #l4_report, #l4_data, #l4_analysis1').hide();
            //$('#l5, #l5_report, #l5_data, #l5_analysis1').hide();
            markersOff();
            // Remove all Features > L0
            removeFeatures(1);
            // Hide this L0 feature
            hideFeature(id);
            // Add the child L1 features to the map
            $.ajax({
                'url': S3.Ap.concat('/static/cache/1_' + id + '.geojson'),
                'dataType': 'json'
            }).done(function(data) {
                var features = parser.read(data);
                var current_projection = map.getProjectionObject();
                for (var prop in features) {
                    // 'remove' is a prop
                    try {
                        if (features[prop].geometry) {
                            features[prop].geometry.transform(proj4326,
                                                              current_projection);
                        }
                    } catch(err) {}
                }
                resilienceLayer.addFeatures(features);
                popupControl.unselectAll();
            }).fail(function(request, status, error) {
                if (error == 'UNAUTHORIZED') {
                    msg = i18n.gis_requires_login;
                } else {
                    msg = request.responseText;
                }
                console.log(msg);
            });
            break;
        case 1:
            if (current_l1 != id) {
                // Restyle the old L1 again
                showFeature(current_l1);
                // Set
                current_l1 = id;
            }
            if (current_l0 != v.f) {
                // Restyle the old L0 again
                showFeature(current_l0);
                // Set
                current_l0 = v.f;
                if (!vdata[current_l0].hasOwnProperty('p')) {
                    // We need to download the other L1s for this L0 (for the Hierarchical Location Selectors)
                    updateL1Menus();
                }
            }
            current_l2 = '';
            current_l3 = '';
            //current_l4 = '';
            //current_l5 = '';
            h = hdata[current_l0];
            l0_name = vdata[current_l0].n;
            l1_name = v.n;
            $('#l2_breadcrumb, #l3_breadcrumb').hide();
            //$('#l4_breadcrumb, #l5_breadcrumb').hide();
            $('#l0_breadcrumb').show().attr('href', 'javascript:v_select_region(0,' + current_l0 + ');');
            $('#l0_breadcrumb span').html(' &raquo; ' + l0_name);
            $('#l1_breadcrumb').show().attr('href', 'javascript:v_select_region(1,' + id + ');');
            $('#l1_breadcrumb span').html(' &raquo; ' + l1_name);
            $('.geoName').html(l1_name);
            type = h.l1;
            $('.geoType').html(type + ' ' + i18n.in_);
            $('#l0_select, #l0_reports, #l0_datas, #l0_analysis1s').val(current_l0);
            $('#l1_select, #l1_reports, #l1_datas, #l1_analysis1s').val(id);
            $('#l2_select, #l2_reports, #l2_datas, #l2_analysis1s').val('');
            $('#l3_select, #l3_reports, #l3_datas, #l3_analysis1s').val('');
            //$('#l4_select, #l4_reports, #l4_datas, #l4_analysis1s').val('');
            //$('#l5_select, #l5_reports, #l5_datas, #l5_analysis1s').val('');
            $('#l1, #l1_report, #l1_data, #l1_analysis1').show();
            $('#l2, #l2_report, #l2_data, #l2_analysis1').show();
            $('#l3, #l3_report, #l3_data, #l3_analysis1').hide();
            //$('#l4, #l4_report, #l4_data, #l4_analysis1').hide();
            //$('#l5, #l5_report, #l5_data, #l5_analysis1').hide();
            markersOff();
            // Remove all Features > L1
            removeFeatures(2);
            // Check if this feature exists
            features = resilienceLayer.getFeaturesByAttribute('id', parseInt(id, 10));
            if (features.length == 0) {
                // Load this feature
                $.ajax({
                    'url': S3.Ap.concat('/static/cache/1_' + current_l0 + '.geojson'),
                    'async': false,
                    'dataType': 'json'
                }).done(function(data) {
                    var features = parser.read(data);
                    var newfeatures = [];
                    var current_projection = map.getProjectionObject();
                    for (var prop in features) {
                        // 'remove' is a prop
                        try {
                            if (features[prop].attributes.id == id) {
                                features[prop].geometry.transform(proj4326,
                                                                  current_projection);
                                newfeatures.push(features[prop]);
                            }
                        } catch(err) {}
                    }
                    resilienceLayer.addFeatures(newfeatures);
                    popupControl.unselectAll();
                }).fail(function(request, status, error) {
                    if (error == 'UNAUTHORIZED') {
                        msg = i18n.gis_requires_login;
                    } else {
                        msg = request.responseText;
                    }
                    console.log(msg);
                });
            }
            // Hide this L1 feature
            hideFeature(id);
            // Add the child L2 features to the map
            $.ajax({
                'url': S3.Ap.concat('/static/cache/2_' + id + '.geojson'),
                'dataType': 'json'
            }).done(function(data) {
                var features = parser.read(data);
                var current_projection = map.getProjectionObject();
                for (var prop in features) {
                    // 'remove' is a prop
                    try {
                        if (features[prop].geometry) {
                            features[prop].geometry.transform(proj4326,
                                                              current_projection);
                        }
                    } catch(err) {}
                }
                resilienceLayer.addFeatures(features);
                popupControl.unselectAll();
            }).fail(function(request, status, error) {
                if (error == 'UNAUTHORIZED') {
                    msg = i18n.gis_requires_login;
                } else {
                    msg = request.responseText;
                }
                console.log(msg);
            });
            break;
        case 2:
            if (current_l2 != id) {
                // Restyle the old L2 again
                showFeature(current_l2);
                // Set
                current_l2 = id;
            }
            if (current_l1 != v.f) {
                // Restyle the old L1 again
                showFeature(current_l1);
                // Set
                current_l1 = v.f;
                if (!vdata.hasOwnProperty(current_l1)) {
                    // Download it
                    $.ajax({
                        'url': S3.Ap.concat('/vulnerability/vdata/' + current_l1),
                        'async': false,
                        'dataType': 'script'
                    }).done(function(data) {
                        // Copy the vdata elements across
                        for (var prop in n) {
                            if (!vdata.hasOwnProperty(prop)) {
                                vdata[prop] = n[prop];
                            }
                        }
                        // Clear the memory
                        n = null;
                    }).fail(function(request, status, error) {
                        if (error == 'UNAUTHORIZED') {
                            msg = i18n.gis_requires_login;
                        } else {
                            msg = request.responseText;
                        }
                        console.log(msg);
                    });
                }
            }
            if (current_l0 != vdata[current_l1].f) {
                // Restyle the old L0 again
                showFeature(current_l0);
                // Set
                current_l0 = vdata[current_l1].f;
                if (!vdata[current_l0].hasOwnProperty('p')) {
                    // We need to download the other L1s for this L0 (for the Hierarchical Location Selectors)
                    updateL1Menus();
                }
            }
            current_l3 = '';
            //current_l4 = '';
            //current_l5 = '';
            h = hdata[current_l0];
            l0_name = vdata[current_l0].n;
            l1_name = vdata[current_l1].n;
            l2_name = v.n;
            $('#l3_breadcrumb').hide();
            //$('#l4_breadcrumb, #l5_breadcrumb').hide();
            $('#l0_breadcrumb').show().attr('href', 'javascript:v_select_region(0,' + current_l0 + ');');
            $('#l0_breadcrumb span').html(' &raquo; ' + l0_name);
            $('#l1_breadcrumb').show().attr('href', 'javascript:v_select_region(1,' + current_l1 + ');');
            $('#l1_breadcrumb span').html(' &raquo; ' + l1_name);
            $('#l2_breadcrumb').show().attr('href', 'javascript:v_select_region(2,' + id + ');');
            $('#l2_breadcrumb span').html(' &raquo; ' + l2_name);
            $('.geoName').html(l2_name);
            type = h.l2;
            $('.geoType').html(type + ' ' + i18n.in_);
            $('#l0_select, #l0_reports, #l0_datas, #l0_analysis1s').val(current_l0);
            $('#l1_select, #l1_reports, #l1_datas, #l1_analysis1s').val(current_l1);
            $('#l2_select, #l2_reports, #l2_datas, #l2_analysis1s').val(id);
            $('#l3_select, #l3_reports, #l3_datas, #l3_analysis1s').val('');
            //$('#l4_select, #l4_reports, #l4_datas, #l4_analysis1s').val('');
            //$('#l5_select, #l5_reports, #l5_datas, #l5_analysis1s').val('');
            $('#l1, #l1_report, #l1_data, #l1_analysis1').show();
            $('#l2, #l2_report, #l2_data, #l2_analysis1').show();
            $('#l3, #l3_report, #l3_data, #l3_analysis1').show();
            //$('#l4, #l4_report, #l4_data, #l4_analysis1').hide();
            //$('#l5, #l5_report, #l5_data, #l5_analysis1').hide();
            // Remove all Features > L2
            removeFeatures(3);
            // Check if this feature exists
            features = resilienceLayer.getFeaturesByAttribute('id', parseInt(id, 10));
            if (features.length == 0) {
                // Load this feature
                $.ajax({
                    'url': S3.Ap.concat('/static/cache/2_' + current_l1 + '.geojson'),
                    'async': false,
                    'dataType': 'json'
                }).done(function(data) {
                    var features = parser.read(data);
                    var newfeatures = [];
                    var current_projection = map.getProjectionObject();
                    for (var prop in features) {
                        // 'remove' is a prop
                        try {
                            if (features[prop].attributes.id == id) {
                                features[prop].geometry.transform(proj4326,
                                                                  current_projection);
                                newfeatures.push(features[prop]);
                            }
                        } catch(err) {}
                    }
                    resilienceLayer.addFeatures(newfeatures);
                    popupControl.unselectAll();
                }).fail(function(request, status, error) {
                    if (error == 'UNAUTHORIZED') {
                        msg = i18n.gis_requires_login;
                    } else {
                        msg = request.responseText;
                    }
                    console.log(msg);
                });
            }
            // Hide this L2 feature
            hideFeature(id);
            // Add the child L3 features to the map
            $.ajax({
                'url': S3.Ap.concat('/static/cache/3_' + id + '.geojson'),
                'dataType': 'json'
            }).done(function(data) {
                var features = parser.read(data);
                var current_projection = map.getProjectionObject();
                for (var prop in features) {
                    // 'remove' is a prop
                    try {
                        if (features[prop].geometry) {
                            features[prop].geometry.transform(proj4326,
                                                              current_projection);
                        }
                    } catch(err) {}
                }
                resilienceLayer.addFeatures(features);
                popupControl.unselectAll();
            }).fail(function(request, status, error) {
                if (error == 'UNAUTHORIZED') {
                    msg = i18n.gis_requires_login;
                } else {
                    msg = request.responseText;
                }
                console.log(msg);
            });
            break;
        case 3:
            if (current_l3 != id) {
                // Restyle the old L3 again
                showFeature(current_l3);
                // Set
                current_l3 = id;
            }
            if (current_l2 != v.f) {
                // Restyle the old L2 again
                showFeature(current_l2);
                // Set
                current_l2 = v.f;
                if (!vdata.hasOwnProperty(current_l2)) {
                    // Download it
                    $.ajax({
                        'url': S3.Ap.concat('/vulnerability/vdata/' + current_l2),
                        'async': false,
                        'dataType': 'script'
                    }).done(function(data) {
                        // Copy the vdata elements across
                        for (var prop in n) {
                            if (!vdata.hasOwnProperty(prop)) {
                                vdata[prop] = n[prop];
                            }
                        }
                        // Clear the memory
                        n = null;
                    }).fail(function(request, status, error) {
                        if (error == 'UNAUTHORIZED') {
                            msg = i18n.gis_requires_login;
                        } else {
                            msg = request.responseText;
                        }
                        console.log(msg);
                    });
                }
            }
            if (current_l1 != vdata[current_l2].f) {
                // Restyle the old L1 again
                showFeature(current_l1);
                // Set
                current_l1 = vdata[current_l2].f;
                if (!vdata.hasOwnProperty(current_l1)) {
                    // Download it
                    $.ajax({
                        'url': S3.Ap.concat('/vulnerability/vdata/' + current_l1),
                        'async': false,
                        'dataType': 'script'
                    }).done(function(data) {
                        // Copy the vdata elements across
                        for (var prop in n) {
                            if (!vdata.hasOwnProperty(prop)) {
                                vdata[prop] = n[prop];
                            }
                        }
                        // Clear the memory
                        n = null;
                    }).fail(function(request, status, error) {
                        if (error == 'UNAUTHORIZED') {
                            msg = i18n.gis_requires_login;
                        } else {
                            msg = request.responseText;
                        }
                        console.log(msg);
                    });
                }
            }
            if (current_l0 != vdata[current_l1].f) {
                // Restyle the old L0 again
                showFeature(current_l0);
                // Set
                current_l0 = vdata[current_l1].f;
                if (!vdata[current_l0].hasOwnProperty('p')) {
                    // We need to download the other L1s for this L0 (for the Hierarchical Location Selectors)
                    updateL1Menus();
                }
            }
            //current_l4 = '';
            //current_l5 = '';
            h = hdata[current_l0];
            l0_name = vdata[current_l0].n;
            l1_name = vdata[current_l1].n;
            l2_name = vdata[current_l2].n;
            l3_name = v.n;
            //$('#l4_breadcrumb, #l5_breadcrumb').hide()
            $('#l0_breadcrumb').show().attr('href', 'javascript:v_select_region(0,' + current_l0 + ');');
            $('#l0_breadcrumb span').html(' &raquo; ' + l0_name);
            $('#l1_breadcrumb').show().attr('href', 'javascript:v_select_region(1,' + current_l1 + ');');
            $('#l1_breadcrumb span').html(' &raquo; ' + l1_name);
            $('#l2_breadcrumb').show().attr('href', 'javascript:v_select_region(2,' + current_l2 + ');');
            $('#l2_breadcrumb span').html(' &raquo; ' + l2_name);
            $('#l3_breadcrumb').show().attr('href', 'javascript:v_select_region(3,' + id + ');');
            $('#l3_breadcrumb span').html(' &raquo; ' + l3_name);
            $('.geoName').html(l3_name);
            type = h.l3;
            $('.geoType').html(type + ' ' + i18n.in_);
            $('#l0_select, #l0_reports, #l0_datas, #l0_analysis1s').val(current_l0);
            $('#l1_select, #l1_reports, #l1_datas, #l1_analysis1s').val(current_l1);
            $('#l2_select, #l2_reports, #l2_datas, #l2_analysis1s').val(current_l2);
            $('#l3_select, #l3_reports, #l3_datas, #l3_analysis1s').val(id);
            //$('#l4_select, #l4_reports, #l4_datas, #l4_analysis1s').val('');
            //$('#l5_select, #l5_reports, #l5_datas, #l5_analysis1s').val('');
            $('#l1, #l1_report, #l1_data, #l1_analysis1').show();
            $('#l2, #l2_report, #l2_data, #l2_analysis1').show();
            $('#l3, #l3_report, #l3_data, #l3_analysis1').show();
            //$('#l4, #l4_report, #l4_data, #l4_analysis1').hide();
            //$('#l5, #l5_report, #l5_data, #l5_analysis1').hide();
            // Remove all Features > L3
            //removeFeatures(4);
            // Check if this feature exists
            features = resilienceLayer.getFeaturesByAttribute('id', parseInt(id, 10));
            if (features.length == 0) {
                // Load this feature
                $.ajax({
                    'url': S3.Ap.concat('/static/cache/3_' + current_l2 + '.geojson'),
                    'async': false,
                    'dataType': 'json'
                }).done(function(data) {
                    var features = parser.read(data);
                    var newfeatures = [];
                    var current_projection = map.getProjectionObject();
                    for (var prop in features) {
                        // 'remove' is a prop
                        try {
                            if (features[prop].attributes.id == id) {
                                features[prop].geometry.transform(proj4326,
                                                                  current_projection);
                                newfeatures.push(features[prop]);
                            }
                        } catch(err) {}
                    }
                    resilienceLayer.addFeatures(newfeatures);
                    popupControl.unselectAll();
                }).fail(function(request, status, error) {
                    if (error == 'UNAUTHORIZED') {
                        msg = i18n.gis_requires_login;
                    } else {
                        msg = request.responseText;
                    }
                    console.log(msg);
                });
            }
            // Hide this L3 feature
            //hideFeature(id);
            // Add the child L4 features to the map
            //$.ajax({
            //    'url': S3.Ap.concat('/static/cache/4_' + id + '.geojson'),
            //    'dataType': 'json'
            //}).done(function(data) {
            //    var features = parser.read(data);
            //    var current_projection = map.getProjectionObject();
            //    for (var prop in features) {
                    // 'remove' is a prop
            //      try {
            //            if (features[prop].geometry) {
            //                features[prop].geometry.transform(proj4326,
            //                                                  current_projection);
            //            }
            //        } catch(err) {}
            //    }
            //    resilienceLayer.addFeatures(features);
            //    popupControl.unselectAll();
            //}).fail(function(request, status, error) {
            //    if (error == 'UNAUTHORIZED') {
            //        msg = i18n.gis_requires_login;
            //    } else {
            //        msg = request.responseText;
            //    }
            //    console.log(msg);
            //});
            break;
        //case 4:
        //    current_l4 = id;
        //    if (current_l3 != v.f) {
                // Restyle the old L3 again
        //        showFeature(current_l3);
                // Set
        //        current_l3 = v.f;
        //        if (!vdata.hasOwnProperty(current_l3)) {
                    // Download it
        //            $.ajax({
        //                'url': S3.Ap.concat('/vulnerability/vdata/' + current_l3),
        //                'async': false,
        //                'success': function(data) {
        //                    // Copy the vdata elements across
        //                    for (var prop in n) {
        //                        if (!vdata.hasOwnProperty(prop)) {
        //                            vdata[prop] = n[prop];
        //                        }
        //                    }
                            // Clear the memory
        //                    n = null;
        //                },
        //                'error': function(request, status, error) {
        //                    if (error == 'UNAUTHORIZED') {
        //                        msg = i18n.gis_requires_login;
        //                    } else {
        //                        msg = request.responseText;
        //                    }
        //                    console.log(msg);
        //                },
        //                'dataType': 'script'
        //            });
        //        }
        //    }
        //    if (current_l2 != vdata[current_l3].f) {
                // Restyle the old L2 again
        //        showFeature(current_l2);
                // Set
        //        current_l2 = vdata[current_l3].f;
        //        if (!vdata.hasOwnProperty(current_l2)) {
                    // Download it
        //            $.ajax({
        //                'url': S3.Ap.concat('/vulnerability/vdata/' + current_l2),
        //                'async': false,
        //                'dataType': 'script'
        //            }).done(function(data) {
                        // Copy the vdata elements across
        //                for (var prop in n) {
        //                    if (!vdata.hasOwnProperty(prop)) {
        //                        vdata[prop] = n[prop];
        //                    }
        //                }
                        // Clear the memory
        //                n = null;
        //            }).fail(function(request, status, error) {
        //                if (error == 'UNAUTHORIZED') {
        //                    msg = i18n.gis_requires_login;
        //                } else {
        //                    msg = request.responseText;
        //                }
        //                console.log(msg);
        //            });
        //        }
        //    }
        //    if (current_l1 != vdata[current_l2].f) {
                // Restyle the old L1 again
        //      showFeature(current_l1);
                // Set
        //      current_l1 = vdata[current_l2].f;
        //        if (!vdata.hasOwnProperty(current_l2)) {
                    // Download it
        //            $.ajax({
        //                'url': S3.Ap.concat('/vulnerability/vdata/' + current_l2),
        //                'async': false,
        //              'dataType': 'script'
        //          }).done(function(data) {
        //                // Copy the vdata elements across
        //                for (var prop in n) {
        //                    if (!vdata.hasOwnProperty(prop)) {
        //                        vdata[prop] = n[prop];
        //                    }
        //                }
                        // Clear the memory
        //                n = null;
        //            }).fail(function(request, status, error) {
        //                if (error == 'UNAUTHORIZED') {
        //                    msg = i18n.gis_requires_login;
        //                } else {
        //                    msg = request.responseText;
        //                }
        //                console.log(msg);
        //            });
        //        }
        //    }
        //    if (current_l0 != vdata[current_l1].f) {
                // Restyle the old L0 again
        //        showFeature(current_l0);
                // Set
        //        current_l0 = vdata[current_l1].f;
        //    }
        //    current_l4 = id;
            //current_l5 = '';
        //    l0_name = vdata[current_l0].n;
        //    l1_name = vdata[current_l1].n;
        //    l2_name = vdata[current_l2].n;
        //    l3_name = vdata[current_l3].n;
        //    var l4_name = v.n;
        //    $('#l5_breadcrumb').hide()
        //    $('#l0_breadcrumb').show().attr('href', 'javascript:v_select_region(0,' + current_l0 + ');');
        //    $('#l0_breadcrumb span').html(' &raquo; ' + l0_name);
        //    $('#l1_breadcrumb').show().attr('href', 'javascript:v_select_region(1,' + current_l1 + ');');
        //    $('#l1_breadcrumb span').html(' &raquo; ' + l1_name);
        //    $('#l2_breadcrumb').show().attr('href', 'javascript:v_select_region(2,' + current_l2 + ');');
        //    $('#l2_breadcrumb span').html(' &raquo; ' + l2_name);
        //    $('#l3_breadcrumb').show().attr('href', 'javascript:v_select_region(3,' + current_l3 + ');');
        //    $('#l3_breadcrumb span').html(' &raquo; ' + l3_name);
        //    $('#l4_breadcrumb').show().attr('href', 'javascript:v_select_region(4,' + id + ');');
        //    $('#l4_breadcrumb span').html(' &raquo; ' + l4_name);
        //    $('.geoName').html(l4_name);
        //    type = h.l4;
        //    $('.geoType').html(type + ' ' + i18n.in_);
        //    $('#l0_select, #l0_reports, #l0_datas, #l0_analysis1s').val(current_l0);
        //    $('#l1_select, #l1_reports, #l1_datas, #l1_analysis1s').val(current_l1);
        //    $('#l2_select, #l2_reports, #l2_datas, #l2_analysis1s').val(current_l2);
        //    $('#l3_select, #l3_reports, #l3_datas, #l3_analysis1s').val(current_l3);
        //    $('#l4_select, #l4_reports, #l4_datas, #l4_analysis1s').val(id);
            //$('#l5_select, #l5_reports, #l5_datas, #l5_analysis1s').val('');
        //    $('#l1, #l1_report, #l1_data, #l1_analysis1').show();
        //    $('#l2, #l2_report, #l2_data, #l2_analysis1').show();
        //    $('#l3, #l3_report, #l3_data, #l3_analysis1').show();
        //    $('#l4, #l4_report, #l4_data, #l4_analysis1').show();
            //$('#l5, #l5_report, #l5_data, #l5_analysis1').hide();
        //    break;
    }
    features = resilienceLayer.getFeaturesByAttribute('id', parseInt(id, 10));
    var prop, i, vx, f;  // scratch vars
    for (prop in features) {
        // 'remove' is a prop
        try {
            var feature = features[prop];
            if (feature.geometry.getArea() !== 0.0) {
                var bounds = feature.geometry.getBounds();
                map.zoomToExtent(bounds);
            }
        } catch(err) {}
    }

    // Enable Markers after the correct Zoom
    switch(level) {
        case 2:
        case 3:
        //case 4:
            markersOn();
            break;
    }

    // @ToDo: something dynamic
    $('.year').html('2012');

    if (level == 3) {
        $('#subGeoDivider').html('');
        $('#subGeoReported').html('');
        $('#subGeoPopup').html('');
    } else {
        $('#subGeoDivider').html('|');
        // Add the child regions
        var count = 0;
        var ratings = [];
        var li;
        for (prop in vdata) {
            if (vdata[prop]['f'] == id) {
                var cr = vdata[prop]['r'];
                if (cr) {
                    li = "<li><div class='ratingBox" + cr + "'>" + cr + '</div><p>' + vdata[prop]['n'] + '</p></li>';
                    ratings.push(li);
                    count++;
                }
            }
        }
        if (count == 1) {
            $('#subGeoReported').html('1 ' + h['l' + (level + 1)] + ' ' + i18n.reported);
        } else {
            // @ToDo: Better i18n
            $('#subGeoReported').html(count + ' ' + h['l' + (level + 1)] + 's ' + i18n.reported);
        }
        var content = "\
            <div class='popupContent'>\
            <ul>" + ratings.join('') + "</ul>\
          </div>\
          <div class='popupBottom'></div>";
        $('#subGeoPopup').html(content);
    }

    // Set the CSS for the Indicator boxes
    var resilience = v.r;
    if (resilience === null) {
        $('#indicator').css('background-color', colors[0]).show();
        $('#mainRating').css('background-color', colors[0]);
    } else {
        $('#indicator').html(resilience);
        $('#mainRating').html(resilience);
        $('#indicator').css('background-color', colors[resilience]).show();
        $('#mainRating').css('background-color', colors[resilience]);
    }

    // Update the Indicator Ratings
    var vi = v.i;
    var found = false;
    for (prop in vi) {
        found = true;
        var p = vi[prop];
        var min = p.min;
        var max = p.max;
        var med = p.med;
        var selector = '#visRange' + prop;
        // Set left margin
        $(selector).css('left', (58 * (min - 1)) + 'px');
        // Set width of the range
        $(selector).css('width', (58 * (max - min)) + 'px');
        // Position the median
        $(selector + ' .medianDot').css('left', (58 * (med - min)) + 'px');
        if (med == min) {
            // Hide the min bar
            $(selector + ' .leftBox').hide();
        } else {
            $(selector + ' .leftBox').show();
        }
        if (med == max) {
            // Hide the max bar
            $(selector + ' .rightBox').hide();
        } else {
            $(selector + ' .rightBox').show();
        }
    }
    if (found) {
        $('.visRange').show();
    } else {
        // No Indicators found, so clear screen
        $('.visRange').hide();
    }

    // Population
    $('#populationCount .listText').html(v.p);
    if (level == 3) {
        // Population Source (doesn't make sense for aggregated data unless all has a common source, which we can't currently tell easily)
        $('#populationCount .popupContent p').html(v.s);
        // Population breakdowns
        $('#dataBreakdown li.breakdown').remove();
        for (prop in v.b) {
            var b = v.b[prop];
            $('#dataBreakdown ul').append("\
            <li class='breakdown'>\
                <p>" + b.n + ":</p>\
                <div class='statistic'>\
                    <div class='listText'>" + b.v + "</div>\
                    <div class='popup'>\
                        <div class='popupContent'>\
                            <p>Source: " + b.s + "</p>\
                        </div>\
                        <div class='popupBottom'></div>\
                    </div>\
                </div>\
            </li>\
            ");
        }
        $('#qualityDescription').hide();
        $('#qualityCommunes').html(i18n.last_data_collected_on + ': ' + v.d);
    } else {
        $('#dataBreakdown li.breakdown').remove();
        $('#qualityDescription').show();
        // Data Quality
        // @ToDo: Better i18n
        $('#qualityCommunes').html(v.c + ' ' + i18n.out_of + ' ' + v.t + ' ' + h.l3 + 's ' + i18n.reported);
        switch(v.q) {
            case 'p':
                $('#poor').addClass('currentQuality');
                $('#fair').removeClass('currentQuality');
                $('#moderate').removeClass('currentQuality');
                $('#strong').removeClass('currentQuality');
                break;
            case 'f':
                $('#poor').removeClass('currentQuality');
                $('#fair').addClass('currentQuality');
                $('#moderate').removeClass('currentQuality');
                $('#strong').removeClass('currentQuality');
                break;
            case 'm':
                $('#poor').removeClass('currentQuality');
                $('#fair').removeClass('currentQuality');
                $('#moderate').addClass('currentQuality');
                $('#strong').removeClass('currentQuality');
                break;
            case 's':
                $('#poor').removeClass('currentQuality');
                $('#fair').removeClass('currentQuality');
                $('#moderate').removeClass('currentQuality');
                $('#strong').addClass('currentQuality');
                break;
        }
        $('#qualityDescription .currentQuality').hover(function() {
            $(this).find('.popup').show();
        }, function() {
            $(this).find('.popup').hide();
        });
    }

    // Update the options for the Hierarchical Dropdowns
    // Reset
    if (current_l1) {
        $('#l1_select, #l1_reports, #l1_datas, #l1_analysis1s').html('<option value="" class="none">' + i18n.choose + ' ' + h.l1 + '</option>');
    } else {
        $('#l1_select, #l1_reports, #l1_datas, #l1_analysis1s').html('<option value="" selected="selected" class="none">' + i18n.choose + ' ' + h.l1 + '</option>');
    }
    if (current_l2) {
        $('#l2_select, #l2_reports, #l2_datas, #l2_analysis1s').html('<option value="" class="none">' + i18n.choose + ' ' + + h.l2 + '</option>');
    } else {
        $('#l2_select, #l2_reports, #l2_datas, #l2_analysis1s').html('<option value="" selected="selected" class="none">' + i18n.choose + ' ' + h.l2 + '</option>');
    }
    if (current_l3) {
        $('#l3_select, #l3_reports, #l3_datas, #l3_analysis1s').html('<option value="" class="none">' + i18n.choose + ' ' + h.l3 + '</option>');
    } else {
        $('#l3_select, #l3_reports, #l3_datas, #l3_analysis1s').html('<option value="" selected="selected" class="none">' + i18n.choose + ' ' + h.l3 + '</option>');
    }
    //if (current_l4) {
    //    $('#l4_select, #l4_reports, #l4_datas, #l4_analysis1s').html('<option value="" class="none">' + i18n.choose + ' ' + h.l4 + '</option>');
    //} else {
    //    $('#l4_select, #l4_reports, #l4_datas, #l4_analysis1s').html('<option value="" selected="selected" class="none">' + i18n.choose + ' ' + h.l4 + '</option>');
    //}
    // Add entries
    var values = [];
    for (prop in vdata) {
        vx = vdata[prop];
        f = vx['f'];
        // || (f == current_l4)
        if ((f == current_l0) || (f == current_l1) || (f == current_l2) || (f == current_l3)) {
            vx['id'] = prop;
            values.push(vx);
        }
    }
    values.sort(nameSort);
    var res, selected;
    for (i=0; i < values.length; i++) {
        vx = values[i];
        res = resilienceClass(vx['r']);
        f= vx['f'];
        var vid = vx['id'];
        if (f == current_l0) {
            if (vid == current_l1) {
                selected = ' selected="selected"';
            } else {
                selected = '';
            }
            $('#l1_select, #l1_reports, #l1_datas, #l1_analysis1s').append('<option value="' + vid + '" class="' + res + '"' + selected + '>' + vx['n'] + '</option>');
        } else if (f == current_l1) {
            if (vid == current_l2) {
                selected = ' selected="selected"';
            } else {
                selected = '';
            }
            $('#l2_select, #l2_reports, #l2_datas, #l2_analysis1s').append('<option value="' + vid + '" class="' + res + '"' + selected + '>' + vx['n'] + '</option>');
        } else if (f == current_l2) {
            if (vid == current_l3) {
                selected = ' selected="selected"';
            } else {
                selected = '';
            }
            $('#l3_select, #l3_reports, #l3_datas, #l3_analysis1s').append('<option value="' + vid + '" class="' + res + '"' + selected + '>' + vx['n'] + '</option>');
        //} else if (f == current_l3) {
        //    if (vid == current_l4) {
        //        selected = ' selected="selected"';
        //    } else {
        //        selected = '';
        //    }
        //    $('#l4_select, #l4_reports, #l4_datas, #l4_analysis1s').append('<option value="' + vid + '" class="' + res + '"' + selected + '>' + vx['n'] + '</option>');
        }
    }
    // Set Labels (i18n?)
    $('#l1 label, #l1_report label, #l1_data label').html(h.l1.toUpperCase() + ':');
    $('#l2 label, #l2_report label, #l2_data label').html(h.l2.toUpperCase() + ':');
    $('#l3 label, #l3_report label, #l3_data label').html(h.l3.toUpperCase() + ':');
    //$('#l4 label, #l4_report label, #l4_data label').html(h.l4.toUpperCase() + ':');

    // Update Select Menus
    updateSelectMenus(false);

    if (!drawerOpen) {
        // Display the ability to open the Drawer
        $('#show-hide').html('<span class="arrow">&uarr;</span> ' + i18n.show_more.toUpperCase()).show();
        $('#divider').show();
        $('#analysisLink').show();
        var image = S3.Ap.concat('/static/themes/Vulnerability/img/openTabPng8.png');
        $('#risingTab').css('background-image', 'url(' + image + ')').show();
    }
}

// function to open/close the drawer
function drawerSlide() {
    switch(drawerOpen) {
        case true:
            // Close
            $('#drawerInside').hide('slow');
            $('#show-hide').html('<span class="arrow">&uarr;</span> ' + i18n.show_more.toUpperCase());
            var image = S3.Ap.concat('/static/themes/Vulnerability/img/openTabPng8.png');
            $('#risingTab').css('background-image', 'url(' + image + ')');
            $('.olPopup').fadeIn(300);
            $('#dummy_location_search').autocomplete('option', 'position', {
                my: 'left bottom',
                at: 'left top'
            });
            drawerOpen = false;
            break;
        case false:
            // Open
            $('#drawerInside').show('slow');
            $('#show-hide').html('<span class="arrow">&darr;</span> ' + i18n.show_less.toUpperCase());
            var image = S3.Ap.concat('/static/themes/Vulnerability/img/closeTabPng8.png');
            $('#risingTab').css('background-image', 'url(' + image + ')');
            $('.olPopup').fadeOut(300);
            $('#dummy_location_search').autocomplete('option', 'position', {
                my: 'left top',
                at: 'left bottom'
            });
            drawerOpen = true;
            break;
    }
}

function goToRegion() {
    // 'Go To Region' has been selected on the Hierarchical Location Selector
    var id;
    //id = $('#l5_select').val();
    //if (id) {
    //    v_select_region(5, id);
    //    return;
    //}
    //id = $('#l4_select').val();
    //if (id) {
    //    v_select_region(4, id);
    //    return;
    //}
    id = $('#l3_select').val();
    if (id) {
        v_select_region(3, id);
        return;
    }
    id = $('#l2_select').val();
    if (id) {
        v_select_region(2, id);
        return;
    }
    id = $('#l1_select').val();
    if (id) {
        v_select_region(1, id);
        return;
    }
    id = $('#l0_select').val();
    if (id) {
        v_select_region(0, id);
    } else {
        globalView();
    }
}

function markersOn() {
    enableVolunteerLayer();
    enableMapLayer();
    var image = S3.Ap.concat('/static/themes/Vulnerability/img/mapIconOnPng8.png');
    $('#mapSection').css('background', 'url(' + image + ') no-repeat center top transparent');
    image = S3.Ap.concat('/static/themes/Vulnerability/img/volunteerIconOnPng8.png');
    $('#volunteerSection').css('background', 'url(' + image + ') no-repeat center top transparent');
    $('#iconsCheck').show();
    $('#iconsKey label').css('color', '#565656');
}
function markersOff() {
    try {
        // Not defined when page first loaded
        disableVolunteerLayer();
        map.removeLayer(mapLayer);
    } catch(err) {}
    var image = S3.Ap.concat('/static/themes/Vulnerability/img/mapIconOffPng8.png');
    $('#mapSection').css('background', 'url(' + image + ') no-repeat center top transparent');
    image = S3.Ap.concat('/static/themes/Vulnerability/img/volunteerIconOffPng8.png');
    $('#volunteerSection').css('background', 'url(' + image + ') no-repeat center top transparent');
    $('#iconsCheck').hide();
    $('#iconsKey label').css('color', '#ccc');
}

// End
